Hi i have the below json
{id:"12",data:"123556",details:{"name":"alan","age":"12"}}
i used the code below to parse
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}}
var jsonobj = JSON.parse(chunk);
console.log(jsonobj.details);
The output that i received is
{"name":"alan","age":"12"}
I need to get the individual strings from details say i should be able to parse and get the value of "name".I am stuck here any help will be much appreciated
If you already have an object, you don't need to parse it.
var chunk={id:"12",data:"123556",details:{"name":"alan","age":"12"}};
// chunk is already an object!
console.log(chunk.details);
// => {"name":"alan","age":"12"}
console.log(chunk.details.name);
//=> "alan"
You only use JSON.parse() when dealing with an actual json string. For example:
var str = '{"foo": "bar"}';
console.log(str.foo);
//=> undefined
// parse str into an object
var obj = JSON.parse(str);
console.log(obj.foo);
//=> "bar"
See json.org for more details
Since jsonobj has already been parsed as a JavaScript Object, jsonobj.details.name should be what you need.
Related
Trying to parse the JSON content from AWS SQS.
First converting a string to JSON String and then to JSON Object. What is the correct way to handle this scenario ?
<script>
// JSON from SQS
var x='{"Message":"{\"default\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
x1=JSON.stringify(x);
var obj = JSON.parse(x1);
console.log(obj.Message); // undefined
alert(obj["Message"]); // undefined
</script>
I have absolutely no idea why you are trying to JSON.stringify() a string. It's already a string!
The string you have got is not valid JSON either and needs a few extra \\s in it. Where did you get it from? Or was it a typo.
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
^__________^_____________________________________________________________^
Just parse the JSON you do have then realise that obj.Message is just more JSON that could be JSON.parse()d
// JSON
var x = '{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
//Parse JSON
var obj = JSON.parse(x);
console.log(obj.Message); // string formatted as yet more JSON
The string is not right. It should be like
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
You are stringifying the x, which is already string
x1=JSON.stringify(x); //Not ok
Im trying to Push a valid json string to javascript json object, but every time im trying to do it like that:
markersData['values'] = [string];
the result is of markersData json object is:
"values":["{'latLng..."
instead of (Original):
"values":[{"latLng...
it take all of the json and push it as one variable (invalid json), how can i push it as a part of the original json?
any idea how to solve it?
Thank you!
You need to deserialise the JSON string before setting it to the property of the object:
markersData['values'] = [JSON.parse(yourJsonString)];
markersData['values'] = [JSON.parse(string)];
Hope this helps.. Read more about JSON.parse here
You need to parse the string first.
JSON.parse(addstringvar);
Code pen demo
var testObj = {};
var addString = '{"name": "test"}';
testObj.values = [JSON.parse(addString)];
You'll need to make sure you have a valid JSON. So below will show you how to create an easy JSON which will be valid for you to use
JSON Object:
var newObject = {};
newObject.Latlng = "ValueHere";
var jsonString = JSON.stringify(newObject);
// Check jsonString before you parse for pushing.
console.log(jsonString);
You will need to deserialise the JSON string before setting it to the
property of the object
like Rory McCrossan mentions in his answer
jsonString[value] = [JSON.parse(jsonString)];
I'm currently processing some json encoded data, but I can't access it properly, this are some tests I did:
Code fragment 1:
var json = [
{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},
{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}];
console.log(json[0][0]);
outputs:
1
Code fragment 2:
var json2 = getCookie('markers');
console.log(json2[0][0]);
outputs:
[
Code fragment 3:
console.log(getCookie('markers'));
output:
[{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}]
as you can see when I use the result from test 3 hardcoded I can access it fine, but when I use it only in code i get something diffrent
does anyone know how to do this?
Cookies only store strings. You need to use JSON.parse() to convert them back to an object. Also, the contents of json isn't JSON but a JAvaScript object (actually, an array).
var obj2 = JSON.parse(getCookie('markers') || '[]');
console.log(obj2[0][0]);
The || '[]' falls back to an empty array if the cookie is missing since an empty string or undefined wouldn't be valid JSON.
The getCookie('markers') returns string. The native javascript method JSON.parse(text[, reviver]) , parse a string as JSON.
var json2 = getCookie('markers');
if ( typeof(json2 ) == "string" ) {
json2 = JSON.parse( json2 );
}
Then try your code ..
i have a json string returned to a hidden value and i want to assign it to a javascript array and print each element of the array.
Json string returned by hdn_client_windows - ["5703","5704"]
Javascript array assignment is as below.
var times = $('#hdn_client_windows').val();
alert(times[0]); // this printed only--> [
alert(times[1]); // this printed only--> "
what am i doing wrong ?
You need to parse the JSON into an array with JSON.parse first:
var times = JSON.parse($('#hdn_client_windows').val());
Since you are already using jQuery, it might be a good idea to defer to $.parseJSON instead just to be on the safe side (full compatibility with old browsers):
var times = $.parseJSON($('#hdn_client_windows').val());
Use $.parseJSON().
var str = '["5703","5704"]';
var times = $.parseJSON( str );
You have to parse the string first using JSON.parse (older browsers might require you to load this in):
var times = JSON.parse($('#hdn_client_windows').val());
alert(times[0]); // Will display first item
alert(times[1]); // Will display second item
You could use jquery's parseJSON() function.
var str = '["5703","5704"]';
var parsed = $.parseJSON( str );
The parsed object now contains the array: ["5703","5704"]
Reference - jQuery.parseJSON( json )
"Takes a well-formed JSON string and returns the resulting JavaScript object."
This code works:
$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});
This code doesn't work:
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);
The question is, how can I make it work?
Your data is not a Javascript object but a string, you can convert it to object by eval e.g.
data = eval('(' + data + ')');
but eval is considered dangerous, so better to parse string as JSON e.g.
data = JSON.parse(data)
For JSON lib you can use json2
It's not JSON, it's a javascript object.
var data = { category: 1 };
If you have a string, you would have to convert it to a object.
And notice that your string is not a valid JSON, see the link for more details.
Take out the quotes, the load function is expecting an object, not a string.
Have you tried to use eval() on data?
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));