I have a string in a Java server application that is accessed using AJAX. It looks something like the following:
var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1", "data": { "$color": "#557EAA" } } ], "data": { "$color": "#EBB056", "$type": "triangle", "$dim": 9 }, "id": "graphnode1", "name": "graphnode1" },{ "adjacencies": [], "data": { "$color": "#EBB056", "$type": "triangle", "$dim": 9 }, "id": "graphnode2", "name": "graphnode2" }];
When the string gets pulled from the server, is there an easy way to turn this into a living JavaScript object (or array)? Or do I have to manually split the string and build my object manually?
Convert JSON String to JavaScript Object The JSON module offers two methods - stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
Modern browsers support JSON.parse()
.
var arr_from_json = JSON.parse( json_string );
In browsers that don't, you can include the json2
library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With