JavaScript JSON
JSON (JavaScript Object Notation) is a text format to store and send data. It looks like a JavaScript object. Almost every web API uses it.
{
"name": "Robin",
"age": 25,
"skills": ["HTML", "CSS"],
"active": true
}
Rules of JSON
- Keys must be in double quotes.
- Strings use double quotes only, not single quotes.
- Values can be string, number, boolean, null, array or object. No functions, no
undefined, no comments. - No trailing comma after the last item.
JSON.stringify: object to text
const user = { name: "Robin", age: 25, skills: ["HTML", "CSS"] };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text);
Output of the above program is
{"name":"Robin","age":25,"skills":["HTML","CSS"]}
string
Use JSON.stringify(obj, null, 2) to get nicely indented text for reading.
JSON.parse: text to object
const json = '{"name":"Maria","age":30}';
const obj = JSON.parse(json);
console.log(obj.name);
console.log(obj.age + 1);
Output of the above program is
Maria
31
Handle wrong JSON
JSON.parse() throws an error if the text is not valid JSON, so wrap it in try...catch (see Error Handling).
try {
JSON.parse("{name: 'Robin'}"); // keys without quotes: invalid
} catch (e) {
console.log(e.name);
}
Output of the above program is
SyntaxError
Copy an object with JSON
const original = { a: 1, list: [1, 2] };
const copy = JSON.parse(JSON.stringify(original));
copy.list.push(3);
console.log(original.list);
Output of the above program is
[ 1, 2 ]
This makes a deep copy, but it loses functions, undefined and dates. The newer structuredClone() is a better choice.
Summary
- JSON is text. Keys and strings need double quotes.
JSON.stringify()turns an object into JSON text,JSON.parse()does the reverse.- Always use
try...catchwithJSON.parse(). - Next: JavaScript Date.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |