Using JSON in JavaScript
Last updated:
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write for both humans and machines, and is often used to exchange data between the client and the server.
A JSON object is a collection of key-value pairs, where each key is a string and each value can be any valid JSON data type, including strings, numbers, boolean values, arrays, and other JSON objects. The key-value pairs are separated by commas and enclosed in curly braces. Here’s an example of a simple JSON string:
{
"name": "Paul",
"city": "London"
}
## The JSON object
```javascript
const person = {
"name": "Paul",
"city": "London"
};
const personJSON = JSON.stringify(person);
const backToPersonAgain = JSON.parse(personJSON);
JSON.stringify replacer
JSON.stringify() can take a second parameter which can be used to specify what properties of the object should be included in the JSON string - this is particularly useful if you want only certain properties to be set to a web endpoint:
const person = {
"name": "Paul",
"city": "London"
};
function replacer(key, value) {
if(key === "city") {
return undefined;
}
return value;
};
const personJSON = JSON.stringify(person, replacer);
// personJSON is: '{"name":"Paul"}'
JSON.parse reviver
JSON.parse() can take a second parameter which can be used to transform the JSON object before it is returned:
const person = {
"name": "Paul",
"city": "London"
};
const personJSON = JSON.stringify(person);
function reviver(key, value) {
if(key === "city") {
return "New York";
}
return value;
};
const backToPersonAgain = JSON.parse(personJSON, reviver);
// backToPersonAgain is: { name: 'Paul', city: 'New York' }