Apply Now Apply Now Apply Now
header_logo
Post thumbnail
WEB DEVELOPMENT

How to Open a JSON File? A Complete Guide on Creating and Reading JSON

By Abhishek Pati

JSON (JavaScript Object Notation) has become one of the most widely accepted data formats among many tech giants and startups. From building web applications to full-fledged systems, it plays an integral role in ensuring the readability and consistency of the data in those software products. Think of it like a connector that bridges the gap between different platforms, enabling seamless data exchange without any technical hindrances.

Without JSON format, it would be quite challenging for software developers and programmers to handle the data conversions, manage file types, and maintain stability across multiple platforms. With its support, the scalability and flexibility of the projects can be significantly enhanced, making it easier to integrate new features and functionalities or connect with external systems without disrupting the existing workflow.

In this blog, we will explore JSON files and learn how to open a JSON file and read them. So, let’s begin.

Table of contents


  1. What Is a JSON File?
  2. How to Create a JSON File
  3. How to Open a JSON File
    • Opening a JSON File on Windows:
    • Opening JSON File on Mac:
    • Opening JSON File Online:
    • Opening JSON File in Code Editors:
  4. How to Read a JSON File
  5. How to Edit a JSON File
  6. Best Practices for Working with JSON Files
  7. Did You Know?
  8. Conclusion
  9. FAQs
    • Is JSON stored as an object in files?
    • How do I edit a JSON file in JavaScript?
    • What are common JSON errors?

What Is a JSON File?

01@2x 2 1

Before understanding JSON files, let’s know the definition of JSON.

JSON (JavaScript Object Notation) is a light-weight data format that stores and transmits data objects in human-readable text. It organizes and structures the data using key-value pairs and arrays, making it easier for both humans and machines to comprehend.

A JSON file is a collection of data and information in a simple text format, allowing users to view the data as objects. Objects have properties attached to them, and these properties contain the information in the form of an array of objects. 

The JSON files are used extensively to transfer data between applications, APIs, and servers, establishing a strong connectivity among different components in the software architecture. These files don’t consume excessive memory and storage, are easier to read and write, and require minimal resources. This simplicity and broad compatibility of JSON files make them an essential element for developing modern age apps.

We are using JavaScript as our primary language to understand the JSON examples below. Note that developers can use any programming language, such as Python, Java, C#, or PHP, to work with JSON.

Explore our free resources to delve deep into the concepts of JavaScript: JS eBook

How to Create a JSON File

02@2x 2 1
const fs = require('fs').promises;

const data = {

    name: "Abhishek",

    age: 25,

    skills: ["JavaScript", "React", "Node.js"]

};

async function createJSONFile() {

    try {

        await fs.writeFile('data.json', JSON.stringify(data, null, 4));

        console.log("JSON file created successfully!");

    } catch (err) {

        console.error("Error writing file:", err);

    }

}

createJSONFile();

Explanation:

  • Here, we have used the fs (file system) module, a built-in Node.js library, to allow the JavaScript code to interact with the computer’s file system.
  • const fs = require(‘fs’).promises. This line loads the fs module with promises in Node.js, allowing us to perform async/await operations instead of executing callbacks.   
  • Now, in this case, we have created a data variable and initialized it with an object that contains the following information in key-value pairs, such as “name”: “Abhishek”, “age”: 25, and “skills”: [“JavaScript”, “React”, “Node.js”].   
  • But kindly remember that data can be stored in a JSON file as text only, which is why we implemented the JSON.stringify(data, null, 4) method to convert the data object into a JSON-formatted string. Inside this function, the null parameter is used to modify keys, but since we don’t want that, it is set to null. The last parameter is set to 4 for indentation, making the JSON file readable instead of a long line.
  • You can see the createJSONFile() function, which is used to perform an asynchronous operation for creating a new JSON file data.json() and writing the JSON string into it. Here, the await keyword is used to tell the JS code to wait for the create operation to complete before moving on. Additionally, the errors are handled by using the try/catch block. At last, we have finally invoked the function.
MDN

How to Open a JSON File

03@2x 2 1

1. Opening a JSON File on Windows:

Opening a JSON file on Windows is a simple task. You just have to right-click the file, choose the “Open with” option, and then select either Notepad or VS Code. Choosing Notepad to open the JSON file will give you plain text, whereas VS Code shows you the data format in colored syntax, making it easier to understand the information structure.

2. Opening JSON File on Mac:

Similar to Windows, when you open a JSON file on macOS, you have to right-click it and select the “Open With” option. The only difference is that instead of Notepad, there will be a TextEdit app to view JSON as plain text, while VS Code is for better readability.

3. Opening JSON File Online:

To open a JSON file online, you can visit websites like json-editor-online. You only need to upload your JSON file or paste the content structure, and the platform will display it in a well-structured and easy-to-read format. In these kinds of sites, along with opening and editing the JSON files, you can also validate them.

4. Opening JSON File in Code Editors:

There are multiple code editors, such as VS Code, Atom, Sublime Text, and many more, that help users open JSON files. These powerful apps highlight the syntax and elements within the JSON file interactively and colorfully, automatically indent the data, and enable navigation through nested structures. Opening JSON files in code editors is beneficial for developers who frequently read or edit them.

How to Read a JSON File

04@2x 1 1
const fs = require('fs');

// Read JSON file

fs.readFile('data.json', 'utf-8', (err, jsonString) => {

    if (err) {

        console.log("File read failed:", err);

        return;

    }

    try {

        const data = JSON.parse(jsonString);      // Convert JSON string to JS object

        console.log(data);

        console.log("Name:", data.name);

        console.log("Skills:", data.skills);

    } catch (err) {

        console.log("Error parsing JSON:", err);

    }

});

Explanation:

  • We have imported the fs (File System) module as it allows us to read, write, and manage files. Inside this module, readFile is a function that we have accessed as fs.readFile. It is an asynchronous function that helps in reading the content of the JSON file (data.json) without blocking the main JS thread, and returns the content as a text string through a callback ( (err, jsonString) => { … } ).
  • In this code statement, ‘ fs.readFile(‘data.json’, ‘utf-8’, (err, jsonString) => { … }) ‘, we are calling the function and asking Node.js to read the data.json file. The second parameter ‘utf-8’ specifies the backend to decode the file bytes into a string using the UTF-8 encoding. Without the UTF-8 encoding, we would get a raw binary form of data.
  • The third parameter is the callback function, which has two parameters: err (to detect errors) and jsonString (to hold the JSON content as a text string).
  • Now, inside this callback, we first apply an if condition to check for reading errors, such as when the file doesn’t exist or lacks permissions. Then we have implemented a try…catch block for handling JSON parsing.
  • Here, we have converted the JSON string to JS object data. If any error occurs in the JSON file, such as missing commas, incorrect data types, or incorrect quotes, we wrap the code in a try/catch block. If parsing succeeds, we can print the data object to the console; if it fails, we can log an error message.

How to Edit a JSON File

05@2x 1 2
const fs = require('fs');

// Read JSON file

fs.readFile('data.json', 'utf-8', (err, jsonString) => {

    if (err) {

        console.log("File read failed:", err);

        return;

    }

    try {

        const data = JSON.parse(jsonString);   // Convert JSON string to JS object

        // Modify the object

        data.age = 26;

        data.skills.push("Node.js");

        // Save updated object back to JSON file

        fs.writeFile('data.json', JSON.stringify(data, null, 4), (err) => {

            if (err) throw err;

            console.log("JSON file updated successfully!");

        });

    } catch (err) {

        console.log("Error parsing JSON:", err);

    }

});

Explanation:

  • To modify the object in memory in this example, we have used the push method (data.skills).push(“Node.js”) for adding the property to the existing skills array, and also directly updated the age property by specifying a new number (data.age = 26).
  • Once the object is modified, you need to save the changes back to the file. This is done with fs.writeFile(‘data.json’, JSON.stringify(data, null, 4), (err) => { … }).

Best Practices for Working with JSON Files

The following are the best practices while working with the JSON files:

  • Validate JSON – Check formatting before parsing.
  • Use UTF-8 encoding – Ensures readable text, not raw bytes.
  • Handle errors – Always catch parsing and file I/O errors.
  • Stringify with indentation – Makes JSON human-readable.
  • Avoid unsupported data – Only use strings, numbers, booleans, arrays, objects, or null.

Did You Know?

💡 Did You Know?

JSON was created by Douglas Crockford in 2001 as a lightweight, language-independent format for exchanging data and is now used in almost all programming languages.

Access career support, real-time projects, and expert-led training, all on one platform. A great deal, isn’t it? If you want to avail these benefits and want to build a highly successful tech career, then get enrolled in the IITM Pravartak Certified MERN Full Stack Development Course with AI Integration. Equip yourself with all the essential technical skills and land a position at top product-based companies.

Conclusion

Today, we learned how to create, read, and edit JSON files in JavaScript, understood the difference between JSON as a string in files and JavaScript objects in memory, explored error handling and common JSON mistakes, and discussed modern async/await methods and best practices for working with JSON efficiently and safely.

FAQs

Is JSON stored as an object in files?

No, JSON files store text strings. You must use JSON.parse() to convert the text into a JavaScript object.

How do I edit a JSON file in JavaScript?

Read the JSON into an object, modify it in memory, then write it back using fs.writeFile() or fs.promises.writeFile()

MDN

What are common JSON errors?

Typical errors include missing commas, missing braces/brackets, wrong quotes, trailing commas, or unescaped characters.

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. What Is a JSON File?
  2. How to Create a JSON File
  3. How to Open a JSON File
    • Opening a JSON File on Windows:
    • Opening JSON File on Mac:
    • Opening JSON File Online:
    • Opening JSON File in Code Editors:
  4. How to Read a JSON File
  5. How to Edit a JSON File
  6. Best Practices for Working with JSON Files
  7. Did You Know?
  8. Conclusion
  9. FAQs
    • Is JSON stored as an object in files?
    • How do I edit a JSON file in JavaScript?
    • What are common JSON errors?