Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a JSON into a JavaScript object

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?

like image 811
mj_ Avatar asked Jun 26 '11 22:06

mj_


People also ask

How do I convert a JSON file to an object?

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.

How do I deserialize JSON?

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.

Can JSON be converted to JavaScript?

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.


1 Answers

Modern browsers support JSON.parse().

var arr_from_json = JSON.parse( json_string ); 

In browsers that don't, you can include the json2 library.

like image 177
user113716 Avatar answered Nov 05 '22 18:11

user113716