json parse
- A common use of JSON is to exchange data to/from a web server.
- The
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string. JSON.parse()
method will parse the JavaScript string and return a JavaScript object.
Syntax
JSON.parse(text); JSON.parse(text, reviver);
Parameters
text
– The string to parse as JSON.reviver
– Optional – function that checks each property, before returning the value.
Return value
The Object
, Array
, string
, number
, boolean
, or null
value corresponding to the given JSON text.
how to parse json in javascript
const json = '{"name": "Alex", "framwork": "VueJS"}'; const obj = JSON.parse(json); console.log(typeof json) console.log(obj) console.log(typeof obj)
Output
string { name: 'Alex', framwork: 'VueJS' } object
For example take an object called obj
which has a nested object.
const obj = { role: 'FrontEndDev', somewhat: { framework: 'SvelteJS' } };
The object is first transformed into a string and then this string will be parsed and converted into an object before being returned.
const parsed = JSON.parse(JSON.stringify(obj)); console.log(typeof obj) console.log(typeof JSON.stringify(obj)) console.log(typeof parsed) console.log(parsed)
- The
JSON.stringify
andJSON.parse
methods can be used to deep copy an object.- In a deep copy, the source and target objects have different memory addresses and are not connected at all.
- The
JSON.stringify()
method will take a JavaScript object as an argument and transform it into a string.- Then the
JSON.parse()
method will parse the JavaScript string and return a JavaScript object.
Output
object string object { role: 'FrontEndDev', somewhat: { framework: 'SvelteJS' } }
Browser Support
Attributes | Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|---|
parse | 3 | 12 | 3.5 | 10.5 | 4 |