The JSON string is a handy format to switch information between terminals. Virtually all the API responses you see are in JSON string format.
The JSON string ought to be parsed to learn the information bundled with this string.
The beneath fast instance has an enter JSON string having properties of animals. The properties are saved in a multi-level hierarchy.
The JSON.parse() JS perform converts this JSON string enter into an object array.
The above code will log the output of the transformed JSON into the browser’s developer console.
animals: Lion: Location: 1: zoo-1: "San Diego Zoo" zoo-2: "Bronx Zoo" identify: "Lion" sort: "Wild"
The supply JSON string could be from many alternative assets. For instance,
- It may be saved within the database that’s to be parsed.
- It may be a response to an API.
The JSON string will include many forms of information like dates, capabilities and extra.
How the date within the JSON string might be transformed
If the enter JSON string comprises date values, the JSON.parse() JS perform ends in a date string.
For instance, the date in
Tue Nov 25 2014 05:30:00 GMT+0530.
Tue Nov 25 2014 05:30:00 GMT+0530
If a JSON script comprises a perform as its worth, the beneath code reveals the right way to parse the enter JSON. In an earlier tutorial, we’ve see many capabilities of JSON dealing with utilizing PHP.
Notice: Utilizing the JS eval() is a nasty thought if you’re working with delicate information. So keep away from utilizing capabilities as a string inside a JS JSON enter.
In a earlier instance, we parsed the date as a string after which transformed it right into a Date object.
As a substitute of changing the resultant Date string right into a Date object later, this program makes use of JSON.parse() with its reviver parameter.
The reviver parameter is a callback perform created beneath to transform the enter date right into a Date object.
The reviver parameter is non-obligatory whereas utilizing the JSOM.parse perform. The callback outlined as a reviver will examine every merchandise of the enter JSON string.