How to Read and Write JSON in JavaScript
JSON is one of the Web’s most widely used and popular data formats. In detail, JSON is derived from JavaScript and shares a similar syntax to JavaScript objects. As many Web applications are built with JavaScript and use JSON to communicate, JavaScript developers must know how to work with JSON.
In this article, you will learn everything you need to know to become an expert when it comes to using JSON in JavaScript. Specifically, you will see how to serialize and parse JSON in JavaScript and read and write JSON files in JavaScript with Node.js.
Let’s dig into how to deal with the JSON format in JavaScript, both in the front and back end!
JavaScript and JSON
JSON stands for JavaScript Object Notation, and although it is clearly related to JavaScript, the two are not the same. Specifically, JSON is a data exchange format based on a subset of JavaScript syntax. JSON is a lightweight format, and its strengths are that it is easy for humans to read and for machines to parse. Check our guide to learn more about the JSON format.
On the other hand, JavaScript is a weakly typed programming language used primarily for front-end and back-end development. Since Web applications generally communicate in JSON format, JavaScript natively offers methods to convert a JavaScript object to JSON and vice versa.
Let’s now learn how to read and write with JSON in JavaScript.
JSON Serialization in JavaScript
JavaScript natively comes with the JSON
object. This exposes the following two static methods:
JSON.stringify()
: To convert a JavaScript array, object, or primitive value to a JSON stringJSON.parse()
: To convert a JSON string to the corresponding JavaScript array, object, or primitive value.
Let’s now learn how to use these two methods.
You can use JSON.stringify()
to serialize a JavaScript object to a JSON string as follows:
// defining a JavaScript object
const user = {
id: 5,
firstName: "Maria",
lastName: "Williams",
age: 34,
email: "m.williams@example.com",
address: {
streetAddress: "123 Main St",
city: "Anytown",
state: "US",
postalCode: "12345",
},
phoneNumbers: [
{
type: "home",
number: "555-555-5554",
},
{
type: "work",
number: "555-555-5555",
},
],
};
// converting user to JSON
const userJSON = JSON.stringify(user);
// using userJSON in an API body...
In detail, JSON.stringify()
accepts any JavaScript value and returns it as a JSON string. If the value passed as a parameter contains a circular reference or involves a BigInt
, a TypeError
is raised.
As you can verify with console.log(userJSON)
, userJSON
stores:
{
"id": 5,
"firstName": "Maria",
"lastName": "Williams",
"age": 34,
"email": "m.williams@example.com",
"address": {
"streetAddress": "123 Main St",
"city": "Anytown",
"state": "US",
"postalCode": "12345"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-555-5554"
},
{
"type": "work",
"number": "555-555-5555"
}
]
}
This is exactly the JSON representation of the user
JavaScript object. You can now use userJSON
as the body of an HTTP POST
request for logging or more.
Similarly, you can also use JSON.stringify()
on JavaScript arrays and primitive values.
JSON Parsing in JavaScript
Let’s assume you have a string variable containing JSON data and want to parse it into its JavaScript representation. You can achieve this with JSON.parse()
as below:
// a string variable storing JSON data
// coming from an API response
const apiResponse = `{"id":5, "firstName": "Maria", "lastName": "Williams", "age":34, "email": "m.williams@example.com", "address" :{ "streetAddress": "123 Main St", "city": "Anytown", "state": "US", "postalCode": "12345"}, "phoneNumbers":[{"type": "home", "number": "555-555-5554"},{"type": "work", "number": "555-555-5555"}]}`;
// converting JSON to JavaScript
const user = JSON.parse(apiResponse);
Note that JSON.parse()
accepts a valid JSON string value and returns a JavaScript value. In case of invalid JSON data, it throws a SyntaxError
.
Reading/Writing JSON Files in JavaScript
Vanilla JavaScript does not allow you to deal with the file system, but you can do it in your back-end with Node.js.
In detail, the native fs
module enables you to watch, read, and write files in the file system of your back-end application. Since fs
is a native Node.js module, you do not need to install any extra dependencies, and you can require it directly with the following:
const fs = require("fs");
Or in ES6, you can import it with:
import * as fs from "fs";
Note that the fs
module comes with synchronous and asynchronous versions for most of its functions. Synchronous versions block the execution of other code until the file system operation is finished. In contrast, asynchronous versions are based on callbacks and are executed as non-blocking operations. Learn more about blocking vs. non-blocking behavior in Node.js.
Let’s now see how to read and write files in Node.js with the fs.readFile()
and fs.writeFile()
functions.
How to Read a JSON File in Node.js
Let’s assume you have a user.json
file in the same folder as your Node.js script. This JSON file contains the following:
{
"id": 14,
"firstName": "John",
"lastName": "Smith",
"age": 47
}
You can use the fs.readFile()
function to read user.json
in Node.js and convert its content with JSON.parse()
as below:
// importing the fs module
const fs = require("fs");
// reading a JSON file asynchronously
fs.readFile("user.json", (error, data) => {
// if the reading process failed,
// throwing the error
if (error) {
// logging the error
console.error(error);
throw err;
}
// parsing the JSON object
// to convert it to a JavaScript object
const user = JSON.parse(data);
// printing the JavaScript object
// retrieved from the JSON file
console.log(user);
});
Note that the fs.readFile()
function accepts:
- A
filename
string: Contains the file name if saved locally or the absolute path if saved elsewhere. - A
callback
function: The function to call after reading the file. This callback takes the following two parameters:error
: If any error occurred.data
: The content of the file as a string.
fs.readFile()
also accepts a parameter to specify the file’s encoding. If omitted, its default value is `“utf8```.
When run, this script would print:
{ id: 14, firstName: "John", lastName: "Smith", age: 47 }
This is the JavaScript representation of the JSON content stored in user.json
.
You can achieve the same result synchronously with fs.readFileSync()
as follows:
const fs = require("fs");
try {
// reading a JSON file synchronously
const data = fs.readFileSync("user.json");
} catch (error) {
// logging the error
console.error(error);
throw error;
}
// parsing the JSON content
const user = JSON.parse(data);
// logging the content read from a file
console.log(user);
In this case, the fs.readFileSync()
function blocks the code execution until the file is read. Then, it parses it and prints its content. Note the try...catch
statement to handle the potential reading errors.
Great! You now know how to read JSON files in JavaScript with Node.js!
How to Write a JSON File in Node.js
Let’s assume you want to convert an existing JavaScript object to JSON to store it in a data.json
file. You can achieve this with JSON.stringify()
and fs.writeFile()
with:
// importing the fs module
const fs = require("fs");
// initializing a JavaScript object
const user = {
id: 1,
completeName: "Jennifer Jones",
age: 20,
};
// converting the JSON object to a string
const data = JSON.stringify(user);
// writing the JSON string content to a file
fs.writeFile("data.json", data, (error) => {
// throwing the error
// in case of a writing problem
if (error) {
// logging the error
console.error(error);
throw error;
}
console.log("data.json written correctly");
});
Note that fs.writeFile()
requires the following parameters:
- A file string: The file’s path where to write it.
- The content to write: A
string
,Buffer
,TypedArray
, orDataView
object that will be written to the file. - A callback function: The function that is called when the writing process ends, and it accepts the following parameters:
- error: If the operation fails.
fs.writeFile()
also accepts an optional object parameter to specify the file’s encoding (utf8
by default), the file permissions, and more.
Run the script, and you will find a data.json
file containing the following:
{
"id": 1,
"completeName": "Jennifer Jones",
"age": 20
}
This represents the user
JavaScript object in JSON format.
You can get the same output synchronously with fs.writeFileSync()
as below:
const fs = require("fs");
// converting a JS object to JSON
const user = {
id: 1,
completeName: "Jennifer Jones",
age: 20,
};
const data = JSON.stringify(user);
try {
// reading a JSON file synchronously
fs.writeFileSync("data.json", data);
} catch (error) {
// logging the error
console.error(error);
throw error;
}
// logging the outcome
console.log("data.json written correctly");
Here, fs.writeFileSync()
does not involve a callback function because it blocks the code execution until the writing operation is done. In case of an error, the catch
statement will intercept it to handle it.
Congrats! You can now write JSON files in JavaScript.
How to Update a JSON File in Node.js
Let’s now see a complete example involving reading and writing a JSON file to update its content. In this case, the goal is to add a completeName
field to the following user.json
file:
{
"id": 9,
"firstName": "Mary",
"lastName": "Anderson"
}
You can achieve that goal with the following:
const fs = require("fs");
// the .json file path
const JSON_FILE = "user.json";
try {
// reading the JSON file
const jsonData = fs.readFileSync(JSON_FILE);
// parsing the JSON content
const user = JSON.parse(jsonData);
// adding the "completeName" field to
// JavaScript representation of the
// "user.json" file
data["completeName"] = `${user.firstName} ${user.lastName}`;
// updating the JSON file
fs.writeFileSync(JSON_FILE, data);
} catch (error) {
// logging the error
console.error(error);
throw error;
}
At the end of the process, user.json
will contain the following:
{
"id": 9,
"firstName": "Mary",
"lastName": "Anderson",
"completeName": "Mary Anderson"
}
Et voilà! You just learned how to update a JSON file in Node.js.
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.
Importing a JSON file in Webpack
Webpack can natively load JSON static assets. So, in a Webpack-based JavaScript application, you can load a JSON file with a simple ES6 import
as follows:
import data from "./data.json";
// ...
// data is a JavaScript object
// directly containing the JSON content
// parsed from "data.json"
console.log(data.name); // e.g. "John"
This is another way to read JSON files in JavaScript that comes in handy in React applications created with Create React App or Next.js applications created with Create Next App.
Conclusion
The article is over! At this point, you know the relationship between JSON and JavaScript, how to deal with JSON in JavaScript native methods, and how to read and write JSON files with JavaScript in Node.js. Also, you learned how Webpack makes importing JSON files easier.
As seen here, dealing with JSON in JavaScript is easy. In this tutorial, you got all the information you need to start using JSON in JavaScript in both the back-end and front-end.
Thanks for reading!
A TIP FROM THE EDITOR: For more on the JSON format, don’t miss All About The JSON Format!