Как записать данные в json файл javascript
Перейти к содержимому

Как записать данные в json файл javascript

  • автор:

Simple way to Create JSON file for Beginners


If you are new to JSON, initially it might be difficult for you to create a json file and follow the syntax. JSON is known as JavaScript Object Notation .

Standard definition — JSON is an open-standard file format or data interchange format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types (or any other serialisable value).

One of the tips is first create xml file and then convert it to JSON.

JSON is used mainly to retrieve information. Social media platform like Facebook stores information in JSON format. Storing the data in database sometimes is cumbersome job in recent times,MongoDB is one latest DB platform also stores data in JSON format . Also ,data is growing rapidly on internet with rise in population. JSON stores the data in file which is easy to read and find the information.

Let’s take example of Facebook data where user information is stored as JSON . It’s very easier to find the information of user i.e Name,Address,Hobbies, Behaviour etc .

Below is one sample format:

We can clearly see that ,we have maintained a hierarchy and also sub levels .

User has name and name has firstname and lastname field.

But, first time when you construct the json it will be complicated to construct it with proper syntax. So, its better to write a xml first .

Equivalent xml is:-

And then convert it to JSON using online websites available or using Programming API.

How to read and write JSON files in Node.js

JSON is a popular format for sharing data among applications written in different languages. In Node.js applications, JSON has become a convenient choice for storing data thanks to its uniformity and simplicity.

Node.js provides built-in modules that make it easy to work with JSON data. In this article, you'll learn to:

  • Read JSON files from the disk.
  • Write JSON data to a file.
  • Use the fs module to interact with the filesystem
  • Use built-in methods like JSON.parse() and JSON.stringify() to convert data from and to JSON format.
  • Use the global require() method to load a JSON file at startup.

Before I go into details of reading a JSON file, let us first create a new JSON file called databases.json that holds the following JSON data:

The databases.json is a simple file stored on a disk containing a JSON array of objects. Want want to read this file and print the records on the console.

To read the JSON data from the above file, you can use the native fs module. This module provides methods to read, write, watch files, and many other functions to interact with the filesystem. Since it is a native module, you don't need to install anything. Just import it in your code by calling const fs = require('fs') .

The fs module gives us two methods, fs.readFile() and fs.readFileSync() , that can be used to read data from a file. Both these functions do the same thing — reading files from disk. The only difference lies in the way these functions are actually executed.

The fs.readFile() method reads data from a file asynchronously. It doesn't block the execution of the event loop while reading the file. Instead, the control is shifted to the successive line to execute the remaining lines of code. Once the file data becomes available, fs.readFile() invokes the callback function passed to it as an argument.

To read the JSON data from the databases.json file by using the fs.readFile() method, just pass in the name of the file, an optional encoding type, and a callback function to receive the file data:

In the above example, since the fs.readFile() method returns data as a JSON string, we have to use JSON.parse() to parse it to a JSON object. Finally, we use the forEach() loop to print all databases on the console.

Here is the output of the above code:

The fs.readFileSync() method synchronously reads data from a file. Unlike fs.readFile() , it blocks the execution of the event loop until all the data from the file is loaded.

Instead of passing the callback method, you only pass the name of the file to fs.readFileSync() as shown below:

Although the fs.readFileSync() has a clean syntax, you should never use it to read large files as it blocks the execution of the event loop and can drastically impact the application's performance. It is helpful only for reading configuration files on application start before performing any other tasks.

Finally, the last way of reading a JSON file is by using the global require() method. This approach is similar to what you use for loading Node.js modules but also works for loading JSON files.

All you need to do is pass the JSON file path to the require() method, and it will synchronously read and parse the JSON file and return a JSON object ready to be used:

The require() method works exactly like the fs.readFileSync() — read file synchronously, but it is a global method that can be called from anywhere. Moreover, it automatically parses the file content into a JavaScript object.

However, there are a few downsides to using the require() method:

  1. It only reads the file once and caches data; requiring it again just return the cached data.
  2. The file must have the .json extension. Without an extension, the require() method won't treat it as a JSON file.

Because of the above limitations, require() is only suitable for loading static configuration files that don't change often. For reading a dynamic file like databases.json , you should use the fs.readFile() method instead.

Just like fs.readFile() and fs.readFileSync() method, the fs module provides two more functions for writing data files: fs.writeFile() and fs.writeFileSync() .

As the names suggest, the fs.writeFileSync() method writes data to a file synchronously while fs.writeFile() writes data to a file in an asynchronous manner.

To write JSON to a file by using fs.writeFile() , just pass in the path of the file to write data to, the JSON string that you want to write, an optional encoding type, and a callback function that will be executed after the file is written.

Note that if the file doesn't already exist, it will be created; if it does exist, it will be overwritten!

Here is an example:

In the above example, we are storing the JSON object user to the user.json file.

Notice the JSON.stringify() method to convert the JSON object into a JSON string before saving it to disk. If you try to write an object to a file without first stringifying it, your file will be empty and look like the below:

Now, if you execute the above code, you should see the following content in the user.json file:

Technically, that's all you need to write JSON to a file. However, the data is saved as a single line of string in the file.

To pretty-print the JSON object, change the JSON.stringify() method as follows:

Now, if you open the user.json file, you should see the following content:

Finally, the last way to write data to a JSON file is using the fs.writeFileSync() method. It writes data to a file synchronously and blocks the execution of the Node.js event loop until the file is written to disk.

Take a look at the following example that uses fs.writeFileSync() to write a JSON object to a file:

Now that we have learned how to read and write JSON files, what if you want to update an existing JSON file?

We can combine these approaches to use our JSON files as a simple database. Whenever we want to update the JSON file, we can read the contents, change the data, and then write the new data back to the original file.

Here is an example that demonstrates how you can add another record to the databases.json file:

Now, if you execute the above code, you should see a new entry in databases.json as shown below:

If you don't want to manually parse or stringify JSON data each time you read or write to a JSON file, use the jsonfile module instead.

The jsonfile module wraps the fs module and JSON object methods and exposes the same methods as the fs module for reading and writing JSON files.

Type the following command in your project root directory to install the jsonfile module:

To read data from JSON files, the jsonfile module provides readFile() and readFileSync() methods. They are similar to those offered by the fs module, except that they automatically parse the contents of the file into a JSON object:

Similarly, to write data to a JSON file, you can either use the writeFile() or writeFileSync() method:

In this article, we looked at different ways to read and write JSON files, including the fs module, the require() method, and the jsonfile module — a 3rd-party module.

The fs module is a native module that provides functions for both reading and writing files. The fs.readFile() and fs.writeFile() methods can be used to read and write data to JSON files asynchronously. To synchronously interact with the filesystem, there are fs.readFileSync() and fs.writeFileSync() methods available.

You can also use the global require() method to synchronously read and parse a JSON file at startup. However, it only caches the file data and can only be used to read files with the .json extension.

If you want to learn more, take a look at what JSON actually is, and how you can read and write a JSON object to a file in Node.js.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

How to write data to a JSON file using Javascript

For example, I have a .JSON file that has the following:

What would be the javascript code to push another object <"nissan": "sentra", "color": "green">into this .json array to make the .json file look like

The reason I’m asking is I am finding a lot of information online on how to pull data from a .json file using AJAX but not writing new data to the .json file using AJAX to update the .json file with additional data.

Any help would be appreciated!

3 Answers 3

You have to be clear on what you mean by «JSON».

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [] . This one happens to be an array. If you want to add a new element to the array, just push it, as in

The word JSON may also be used to refer to a string which is encoded in JSON format:

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse :

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify :

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify , and use another ajax call to send the data to the server for storage or other manipulation.

You use the term «JSON file». Normally, the word «file» is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a «file». Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a «JSON file», and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your «JSON file» actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?


This tutorial covers pretty print json objects for easily readable, parse json objects, and writing to a json file with examples in Nodejs Application..

  • How to pretty print and format json object
  • How to read the JSOn object
  • Write json file

How to pretty print jSON object in Nodejs Application

PrettyPrint JSOn is easier to read instead of a normal json string and It contains tabs and spaces.

Pretty print is a way of printing JSON objects with correct indentation, tabs, and spaces and these can be easily read by developers.

Please enable JavaScript

This will be very useful for the inspection of a JSON object during debugging.

There are multiple ways we can do it,

Using the JSON.stringify method

JSON stringify method Convert the Javascript object to json string by adding the spaces to the JSOn string and printing in an easily readable format.

JSOn string contains objects without spaces in employee.json

Here is nodejs pretty print example

  • read the file using readFile, which returns a callback of error and data.
  • returned pretty print json object before parsing json content using JSON object

using prettier npm library

prettier is a code formatter that has support for major programming languages.

First, Install a prettier npm library

Here is a code for Prettier to format json

How to read external JSON file in Nodejs Application

It is easy to read json data files in Javascript.

There are multiple ways we can achieve it.

using the readFile method to asynchronous read json file

Let’s have an employee.json file that contains the following data.

JSOn files can be parsed in Asynchronous and Synchronous ways.

How to Asynchronous read and parse JSON file here is a readFile example to read the local external JSON file readFile is an asynchronous operation with callback holding err, an error of file read status, data holds the content of the file

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *