JavaScript & JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and easy for machines to parse and generate.
The Rules of JSON
Although JSON is derived from JavaScript object literal syntax, it is highly strict:
- Property names MUST be enclosed in double quotes.
"name": "Alex"is valid, butname: "Alex"is not. - Values must be a string, number, object, array, boolean, or null.
- Functions, Dates, and
undefinedare NOT supported. - Trailing commas are strictly forbidden.
JSON.stringify()
When sending data to a web server, the data has to be a string. We convert a native JavaScript object into a string with JSON.stringify().
const obj = { name: "Alex", age: 30 };
const myJSON = JSON.stringify(obj);
// myJSON is now '{"name":"Alex","age":30}'JSON.parse()
When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.
const jsonString = '{"name":"Alex","age":30}';
const myObj = JSON.parse(jsonString);
console.log(myObj.name); // Output: AlexView Bonus Trick: Deep Copy+
Because `JSON.stringify` converts an object completely into a string, and `JSON.parse` creates a brand new object from that string, combining both is a common 'hack' to create a Deep Copy of an object, severing all nested references!
const deepCopy = JSON.parse(JSON.stringify(originalObject));