Learning about JSON
JSON JavaScript Object Notation is a lightweight format that is used for data interchanging. All modern browsers support JSON object. JSON objects are surrounded by curly brackets {} and its objects are written in key/value pairs where keys must be string data type and values must be one of the valid JSON data type such as string, number, object, array, boolean, null. Key and values are separated by semicolon.
Example
{ "firstName": "JBC", "lastName": "Edge", "address": { "streetAddress": "43 2nd Street", "city": "New Zealand", "state": "NZ", "postalCode": 00064 }, "phoneNumbers": [ "0215948563", "2928524136" ] }
JSON.stringify
Used to create a JSON string out of an object or array, it serializes a JavaScript object into a JSON string. It turns a Javascript object into JSON text and stores that JSON text in a string. In simple terms is to create a JSON string out of an object or array.
JSON.parse
Used for parsing data that was received as JSON, it deserializes a JSON string into a JavaScript object. Simply it turns a string of JSON text into a JavaScript object
NOTE
In javascript JSON is a string. Not all Javascripts objects are JSON and vice versa.
Example:
var x = {x:y}
This is Javascript object and NOT JSON
var x = '{"x":"y"}';
This is JSON and NOT Javascrpt object
To convert JSON string into Javascript object you need JSON.parse() function
var x = JSON.parse('{"x":"y"}');
Example
const myObj = { name: 'Test', age: 2, city: 'nandi' }; const myObjStr = JSON.stringify(myObj); console.log(myObjStr); // "{"name":"Test","age":2,"city":"nandi"}" console.log(JSON.parse(myObjStr)); // Object {name: "Test", age: 2, city: "nandi"} var myObject = JSON.parse(myObjStr); console.log(myObject.city); //nandi
With Arrays
const myArr = ['carrot', 'spinach', 'tomatoes']; //JSON string const myArrStr = JSON.stringify(myArr); console.log(myArrStr); // "["carrot","spinach","tomatoes"]" //JavaScript object console.log(JSON.parse(myArrStr)); // ["carrot","spinach","tomatoes"] var myObject = JSON.parse(myArrStr); console.log(myObject[0]); //carrot
With Second Argument
JSON.parse()
Can pass second argument as a reviver function to transform object values before they are returned.
const user = { name: 'JBC', email: 'jbc@jbcedge.com', }; const userStr = JSON.stringify(user); JSON.parse(userStr, (key, value) => { if (typeof value === 'string') { return value.toUpperCase(); } return value; });
JSON.stringify()
Can take two additional arguments first one as replacer function and second as string or number value to use as the returned string.
Replacer function can be used as filtered-out values
const user = { id: 12, name: 'JBC', email: 'jbcedge@jbcedge.com' }; function replacer(key, value) { console.log(typeof value); if (key === 'email') { return undefined; } return value; } const userStr = JSON.stringify(user, replacer);
Adding more characters/strings
const userStr1 = JSON.stringify(user, null, '=>'); console.log(userStr1);
Read more here