Using JSON in JavaScript
Last updated: August 24, 2022.
JSON (JavaScript Object Notation) is a universally recognized way of formatting a string to store data inside it.
In other words, JSON is just data in string format.
In JavaScript, it is uncommon to write JSON directly.
Rather, the JSON.stringify()
method is commonly used to convert a native JavaScript object, such as an array or data object, into string format. This way it can be sent to an API in a universally recognized format or stored on a HTML attribute.
Conversely, JSON.parse()
is often used to convert data retrieved from an API call into native JavaScript format.
JavaScript is integrated in the term JSON but it is a language-indepedent format for storing data. JSON files can be created and read by any programming language.
Table of contents
JSON syntax
As mentioned in the introduction, it is rare to write JSON directly in JavaScript. But it is useful to have at least some similarity with the syntax.
JSON syntax is very similar to that of a regular JavaScript object. The main difference is that object keys are in quotation marks:
const data = `
"name": "Michael Jordan",
"age": 59,
"American": true,
"hobbies": [ "Basketball", "Sport", "Watching NBA" ]
`;
When creating a new JSON data object in JavaScript, it is easiest to use template literal syntax (backticks) as above. This way you can create a multi-line string without having to use special syntax for line breaks.
JSON files
You can store JSON string data in a JSON file.
Just save text in the same format as above and save with a .json
extension:
{
"name": "Michael Jordan",
"age": 59,
"American": true,
"hobbies": [ "Basketball", "Sport", "Watching NBA" ]
}
If a JSON file is stored somewhere, you can retrieve it using the Fetch API and convert its payload (JSON file) to a native JavaScript object by calling the response.json()
method on the response object:
async function getThatData() {
try {
// Fetch JSON data from somewhere:
const data = await fetch('./data.json');
// Convert fetch payload to native JS format:
let res = await data.json();
console.log(res); // If successful, logs JS object in console
}
catch(e) {
console.log('Error!', e);
}
};
getThatData();
Converting to and from JSON
JavaScript to JSON with JSON.stringify()
You can convert a native JavaScript object (array or data object) to JSON string format.
Just call JSON.stringify()
, passing in the object to convert in parantheses.
Below, a JavaScript data object is converted to JSON format:
const myJavaScriptObject = {
name: "Tiddles",
type: "Cat",
age: 11,
human: false,
}
const res = JSON.stringify(myJavaScriptObject);
console.log(typeof res, res);
// string {"name":"Tiddles","type":"Cat","age":11,"human":false}
And here's an example of array-to-JSON conversion:
const myJavaScriptArray = ["books", 23, true, { name: "Timmy" } ];
const res = JSON.stringify(myJavaScriptArray);
console.log(typeof res, res);
// string ["books",23,true,{"name":"Timmy"}]
JSON to JavaScript with JSON.parse()
A JSON string can be converted into JavaScript native format using the JSON.parse()
method.
Below, the JSON objects created in the examples above are converted back to native JavaScript objects.
First example, converting the data object from JSON back to native JavaScript format:
const data = '{"name":"Tiddles","type":"Cat","age":11,"human":false}';
const res = JSON.parse(data);
console.log(res);
// {
// "name": "Tiddles",
// "type": "Cat",
// "age": 11,
// "human": false
// }
Second, the array from JSON to JavaScript:
const data = '["books",23,true,{"name":"Timmy"}]';
const res = JSON.parse(data);
console.log(res);
// [
// "books",
// 23,
// true,
// {
// "name": "Timmy"
// }
// ]
readableStream
to JavaScript with response.json()
When making an API request for data, you often received a response containing a readable stream (readbleStream
).
If the readable stream contains data in JSON format, you can apply the response.json()
to the response object to read the stream until completion.
The output is data in native JavaScript format:
async function getThatData() {
try {
// Fetch JSON file from somewhere:
const data = await fetch('./data.json');
// See if readable stream exists:
console.log(data.body); // ReadableStream {locked: false}
// Read stream until completion:
let res = await data.json();
console.log(res); // If successful, native JS object is logged to the console
}
catch(e) {
console.log('Error!', e);
}
};
getThatData();
Note that response.json()
is asynchronous (it takes time to read the stream) and returns a promise.
Therefore, you have to wait for its result using native promise syntax or async/await (above).
Summary
JSON is a language-indepedent format for storing data. Though it was first developed for JavaScript, JSON string format can be read and created in any programming language.
In JavaScript, there are two in-built methods that used for converting to and from JSON:
JSON.stringify()
: JavaScript native format to JSON.JSON.parse()
: JSON to JavaScript native format.
To read a readable stream containing a JSON string to JavaScript native format, use response.json()
.
Related links
- json.org: Official JSON hompage
- MDN Web Docs: Response.json()