Stringify & Parse
The JavaScript JSON object contains two useful methods for parsing JSON and converting it to JSON string.
JSON.stringify()
The JSON.stringify()
method usually converts a JavaScript array or an object into a JSON string. Consider an array called droids
, say, of the well-known droid characters in Star Wars.
var droids = ["R2-D2", "C-3PO", "BB-8"];
The above array can be converted into a JSON string using the command below
var d = JSON.stringify(droids);
Since the variable d
above is assigned to the stringified string, the commands d[0]
and d.length
below
> d[0];
> d.length;
returns the first character ([
) and the total length of the JSON string (24
) respectively.
JSON.parse()
JSON.parse()
does just the opposite of JSON.stringify()
- it parses a well-formed JSON string and returns a JavaScript object. The stringified JSON text in the variable d
above can be converted into a JavaScript object as
JSON.parse(d);
Similarly, we can convert JavaScript objects into JSON strings using the JSON.stringify()
method. Note that in the above section we have applied JSON.stringify()
on an array. Consider the object below
var droid = {
name:"BB-8",
year:2015,
episode:"VII"
};
As with arrays above, the same can be applied to it
var d = JSON.stringify(droid);