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)];
Related
I am trying to parse a simple JSON string using jQuery
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
I would expect typeof(parsedJSON.graph_data) to be an Object but instead it is returning string. What is the correct way to return an Object?
It should be like
var parsedJSON = $.parseJSON('{"graph_data": {}}');
console.log(typeof(parsedJSON.graph_data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
no need of " for object, " is needed for defining string and object key. So it will treat as string here. For more about JSON structure and example visit http://www.json.org/.
try it.
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
console.log(parsedJSON.graph_data);
I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.
In particular, I need the address, postcode, region, and locality.
This JSON array is being stored as a JS var called "data"
Does anyone know how I can begin parsing out those things? Thank you all!
[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and
Dining","Restaurants"]],"country":"us","email":"kimd#thedussingroup.com","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]
Appreciate the help!
You JSON is an array (since it's contained in [ and ]), so you need:
var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
postcode = data[0].postcode;
and so on...
for(var i in data[0]){
window[i] = data[0][i];
}
alert(address);
You can do this using JSON.parse
var data= your json;
JSON.parse(data);
Update:
In your case you don'e even need to parse you can use directly like
console.log(data[0].address); //returns 2801 Elliott Ave
console.log(data[0].category_ids); //returns [347]
Check this JSFiddle
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));