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 ..
Related
Here is my code
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
var json = JSON.parse(JSON.stringify(data));
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
And I can't seem to figure out why I'm not able to access the json object parameter. Anyone know what the issue is?
Thanks in advance.
Let us to some basic debugging:
> var data = '{"coord": ... }';
> typeof data
"string"
So far so good, data is a string.
> JSON.stringify(data);
""{\"coord\": ... }""
> typeof JSON.stringify(data);
"string"
Apparently JSON.stringify(data) also returns a string. We can see the same value contained in data but now including surrounding quotes (note the double "" at the beginning and the end) and escaped quotes (\").
So what exactly does JSON.stringify do? It will convert any JavaScript value to JSON. Some examples:
> JSON.stringify([]) // array
"[]"
> JSON.stringify(true) // array
"true"
> JSON.stringify("foo") // string
""foo""
We can see that passing a string simply produces another JSON encoded string, so that doesn't seem particular helpful. But you are also using JSON.parse, so lets see what effect that has:
> JSON.parse(JSON.stringify(data))
"{"coord": ... }"
> typeof JSON.parse(JSON.stringify(data))
"string"
It seems using JSON.parse returns a string again. This shouldn't be too surprising since we are passing a string value to JSON.stringify, which will encode it as a JSON string. Parsing this result must give us back the original value, which was a string. We can verify that easily:
> JSON.parse(JSON.stringify(data)) === data
true
Yep.
So that doesn't help us converting data to a JavaScript object. Lets just try JSON.parse instead:
> JSON.parse(data)
Object {coord: Object, weather: Array[2], base: "cmc stations", main: Object, wind: Object…}
That looks much better. Since data contains a JSON encoded object, JSON.parse converts that value to a JavaScript object.
I your example, data is a string, not a javascript object, so you don't need to use JSON.stringify, remove it and it should work:
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
//NOTE: only parse is needed
var json = JSON.parse(data);
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
data is a String because of the single quotes , so if you called JSON.stringify(data) will add another double quotes to data , which means in order to convert data to JS object you will need to call JSON.parse(data) two times .
var obj ='{hello:1}'; //string
var json= JSON.stringify(obj);
console.log(json); // "\"{hello:1}\""
console.log(JSON.parse(json)); //"{hello:1}" => still a string
To get your code running correctly by converting data to object , just remove the JSON.stringify()
function setWeather(data) {
var json = JSON.parse(data); // remove JSON.stringify() => now json is object
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
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."
I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;
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.
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));