JSON
JSON stands for JavaScript Object Notation. It is a simple text format used to store and send data.
You will often see JSON in APIs, config files, and when applications send data between frontend and backend.
Why JSON is useful
Section titled “Why JSON is useful”- Easy for humans to read
- Easy for programs to parse
- Works in many programming languages
- Common format for API requests and responses
Basic structure
Section titled “Basic structure”JSON uses:
- Curly braces
{}for objects - Square brackets
[]for arrays - Double quotes
""for keys and string values
Example:
{ "name": "Sara", "age": 20, "isStudent": true}JSON data types
Section titled “JSON data types”JSON supports these value types:
- String
- Number
- Boolean
- Object
- Array
- null
Example:
{ "name": "Sara", "age": 20, "skills": ["HTML", "CSS", "JavaScript"], "address": { "city": "Paramaribo" }, "graduated": false, "nickname": null}JSON rules
Section titled “JSON rules”- Keys must use double quotes
- Strings must use double quotes
- Items are separated by commas
- JSON cannot contain functions
- JSON does not allow
undefined
JSON vs JavaScript object
Section titled “JSON vs JavaScript object”They look similar, but they are not the same.
- JSON is plain text
- A JavaScript object is a value inside JavaScript code
- JSON must use double quotes
JavaScript object:
const user = { name: 'Sara', age: 20 };JSON text:
{ "name": "Sara", "age": 20}Convert JSON in JavaScript
Section titled “Convert JSON in JavaScript”Use JSON.stringify() to turn a JavaScript object into JSON text.
const user = { name: 'Sara', age: 20 };const text = JSON.stringify(user);Use JSON.parse() to turn JSON text into a JavaScript object.
const text = '{"name":"Sara","age":20}';const user = JSON.parse(text);Common mistakes
Section titled “Common mistakes”- Using single quotes instead of double quotes
- Forgetting a comma
- Adding a trailing comma at the end
- Using
undefinedin JSON
Wrong:
{ "name": "Sara"}Correct:
{ "name": "Sara"}