JSON File Handling

A JSON file is a plain text file with a .json extension. It stores data in JSON format so applications can read it, save to it, and share it. JSON files are used for configuration, data storage, API mocking, and transferring data between systems.

What is a JSON File

Imagine a filing cabinet in an office. Each drawer holds a set of organized papers. A JSON file is like one of those drawers — it holds structured data in a format that both humans and computers can read. Unlike a database, a JSON file needs no server. It sits on your hard drive and works with any text editor.

A Simple JSON File (users.json)

[
  {
    "id": 1,
    "name": "Ankita Rao",
    "email": "ankita@example.com"
  },
  {
    "id": 2,
    "name": "Dev Kumar",
    "email": "dev@example.com"
  }
]

Save this text in a file named users.json. Any application can now read this file and work with the data inside.

JSON File Naming Rules

  • Use the .json extension.
  • Use lowercase letters and hyphens: user-profile.json, product-list.json.
  • Avoid spaces in file names.
  • Use descriptive names that reflect the content: config.json, orders.json.

Reading a JSON File in JavaScript (Node.js)

Node.js provides two main ways to read a JSON file: using require() for simple cases and using the fs module for more control.

Method 1: Using require() — Simple and Fast

// Node.js reads and parses the file automatically
const users = require('./users.json');

console.log(users[0].name); // Ankita Rao

The require() method reads the file, parses the JSON, and returns a JavaScript object. This method is synchronous and works well for configuration files that load once at startup.

Method 2: Using the fs Module — More Control

const fs = require('fs');

// Asynchronous reading (does not block other code)
fs.readFile('./users.json', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  const users = JSON.parse(data);
  console.log(users);
});

The fs.readFile() method reads the file in the background. When the file is ready, it calls the function with the content. You then use JSON.parse() to convert the string into a usable object.

Method 3: Using fs.promises (Modern Async/Await)

const fs = require('fs').promises;

async function loadUsers() {
  const data = await fs.readFile('./users.json', 'utf8');
  const users = JSON.parse(data);
  return users;
}

loadUsers().then(users => console.log(users));

Writing a JSON File in Node.js

Writing to a JSON file means converting your JavaScript object to a string with JSON.stringify() and then saving it.

Writing Data to a JSON File

const fs = require('fs');

const newUser = { id: 3, name: "Sara Joshi", email: "sara@example.com" };

// Convert object to formatted JSON string
const jsonString = JSON.stringify(newUser, null, 2);

fs.writeFile('./new-user.json', jsonString, 'utf8', (err) => {
  if (err) {
    console.error('Error writing file:', err);
    return;
  }
  console.log('File saved successfully!');
});

The second argument null and third argument 2 in JSON.stringify() add two-space indentation. This makes the output file readable.

Diagram: Read and Write Flow

READING A JSON FILE
--------------------
users.json (disk)
    |
    v
fs.readFile() reads raw text
    |
    v
JSON.parse() converts text to object
    |
    v
JavaScript object ready to use

WRITING A JSON FILE
--------------------
JavaScript object
    |
    v
JSON.stringify() converts object to text
    |
    v
fs.writeFile() saves text to disk
    |
    v
users.json updated on disk

Reading and Writing JSON Files in Python

Python makes JSON file handling very clean with the built-in json module.

Reading a JSON File in Python

import json

with open('users.json', 'r', encoding='utf-8') as file:
    users = json.load(file)

print(users[0]['name'])  # Ankita Rao

The json.load() function reads the file and parses it in one step. The with statement automatically closes the file after reading.

Writing a JSON File in Python

import json

new_user = {"id": 3, "name": "Sara Joshi", "email": "sara@example.com"}

with open('new-user.json', 'w', encoding='utf-8') as file:
    json.dump(new_user, file, indent=2)

print("File saved!")

The json.dump() function converts the Python dictionary to JSON and writes it directly to the file. The indent=2 argument formats the output with two spaces.

Reading and Writing JSON Files in PHP

Reading a JSON File in PHP

<?php
$content = file_get_contents('users.json');
$users = json_decode($content, true);

echo $users[0]['name']; // Ankita Rao
?>

Writing a JSON File in PHP

<?php
$newUser = ["id" => 3, "name" => "Sara Joshi", "email" => "sara@example.com"];
$jsonString = json_encode($newUser, JSON_PRETTY_PRINT);
file_put_contents('new-user.json', $jsonString);
echo "File saved!";
?>

Real-World Use Case: Config File

Many applications use a config.json file to store settings. Instead of hardcoding values inside the code, you place them in the JSON file. When you need to change a setting, you edit the file — not the code.

config.json

{
  "appName": "MyShop",
  "version": "2.1.0",
  "database": {
    "host": "localhost",
    "port": 5432,
    "name": "myshop_db"
  },
  "currency": "INR",
  "maxCartItems": 10
}

Reading the Config in Node.js

const config = require('./config.json');

console.log(config.appName);         // MyShop
console.log(config.database.port);   // 5432

Updating a JSON File (Read → Modify → Write)

The standard pattern for modifying a JSON file is: read the file, change the data in memory, write it back.

const fs = require('fs');

// Step 1: Read
const data = fs.readFileSync('./users.json', 'utf8');
const users = JSON.parse(data);

// Step 2: Modify
users.push({ id: 3, name: "Sara Joshi", email: "sara@example.com" });

// Step 3: Write back
fs.writeFileSync('./users.json', JSON.stringify(users, null, 2), 'utf8');

console.log("User added!");

Common Errors When Handling JSON Files

Error 1: File Not Found

Happens when the file path is wrong. Check if the file name and directory path are correct.

Error 2: Invalid JSON in File

Happens when the file contains invalid JSON. Use a JSON validator tool to find syntax errors before reading the file in code.

Error 3: Encoding Issues

Always specify utf-8 encoding when reading or writing files to avoid garbled characters in names and text.

Error 4: Race Conditions in Async Code

When multiple parts of your code read and write the same JSON file at the same time, data can get corrupted. Use locks or a proper database for concurrent writes.

JSON Files vs Databases

JSON File                   Database
---------                   --------
Good for small data         Good for large data
No setup needed             Requires installation
No concurrent writes        Supports concurrent writes
Human-readable              Optimized for speed
Good for config/mock data   Good for production apps

Summary

JSON files store structured data in plain text. You read them by parsing the text into objects and write them by converting objects back to text. Node.js, Python, and PHP all have built-in tools for JSON file handling. Use JSON files for configuration, small data sets, and API mocking. For large-scale or concurrent data needs, use a proper database instead.

Leave a Comment

Your email address will not be published. Required fields are marked *