What Is JavaScript Object Notation (JSON)?
JavaScript Object Notation, or JSON, is a lightweight data interchange format that's easy for humans to read and write—and easy for machines to parse and generate. It has become the de facto standard for sending data in web applications, APIs, and configuration files. Whether you’re building a RESTful API or storing settings for a Node.js script, you’ll almost certainly be working with JSON.
But what makes JSON so powerful? How does it differ from plain JavaScript objects? And how do you safely parse, manipulate, and persist JSON data in a real project? In this article, we'll explore the syntax rules, parsing methods, common pitfalls, and practical Node.js examples. By the end, you'll know exactly how to work with JSON in your next JavaScript or Node.js app.
JSON Syntax Basics
JSON is a text format composed of two structures:
-
Objects: Unordered collections of key/value pairs, wrapped in
{}
. -
Arrays: Ordered lists of values, wrapped in
[]
.
Keys must be strings in double quotes, and values can be:
- Strings (
"hello"
) - Numbers (
42
,3.14
) - Booleans (
true
,false
) null
- Objects (
{ "nested": true }
) - Arrays (
[1, 2, 3]
)
{
"user": "alice",
"age": 30,
"active": true,
"roles": ["admin", "editor"],
"profile": {
"email": "alice@example.com"
}
}
Tip: Always use a JSON linter or an editor with syntax checking to avoid missing commas or incorrect quotes.
Parsing and Stringifying
In JavaScript, you convert between JSON text and objects with the global JSON
object:
const jsonString = '{"name":"Bob","score":85}';
// Parse JSON text to JavaScript object
const data = JSON.parse(jsonString);
console.log(data.name); // "Bob"
// Modify object
data.score = 90;
// Convert object back to JSON text
const updated = JSON.stringify(data, null, 2);
console.log(updated);
Key points:
-
JSON.parse()
will throw an error if the text isn’t valid JSON. -
JSON.stringify()
can take optional replacer and spacing arguments for custom output. - Avoid using
eval()
to parse JSON—always useJSON.parse()
for safety.
JSON vs JavaScript Objects
Although JSON’s syntax mirrors JavaScript object notation, they’re not identical:
Aspect | JavaScript Object | JSON Text |
---|---|---|
Key quotes | Optional | Required (double quotes) |
Trailing commas | Allowed in modern engines | Not allowed |
Functions & Symbols | Permitted | Not allowed |
Comments | Allowed in code | Not allowed |
// JavaScript object
const obj = {
name: 'Jane', // comment is allowed
sayHi() { console.log('Hi'); },
};
// JSON text (no comments, no functions)
const jsonText = '{"name":"Jane"}';
JSON is purely data. If you need methods or custom types, store the minimum data in JSON and reconstruct logic after parsing.
Working with JSON in Node.js
Node.js makes it easy to read and write files. Here’s a basic example:
import { promises as fs } from 'fs';
async function loadConfig(path) {
const raw = await fs.readFile(path, 'utf8');
return JSON.parse(raw);
}
async function saveConfig(path, config) {
const text = JSON.stringify(config, null, 2);
await fs.writeFile(path, text, 'utf8');
}
(async () => {
const cfg = await loadConfig('./config.json');
cfg.lastRun = new Date().toISOString();
await saveConfig('./config.json', cfg);
})();
For more advanced file checks, see how to check if a file exists before reading. To learn how to save JSON data to a file in Node.js with error handling and backups, check our guide.
JSON in HTTP and APIs
When building web APIs or calling endpoints, JSON is almost always the payload format:
// Using fetch in the browser or node-fetch
fetch('/api/users')
.then(res => res.json())
.then(users => console.log(users));
// Using axios in Node.js
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(res => console.log(res.data));
In Node.js, you might need to craft HTTP requests manually. Learn more in our guide on making HTTP requests in Node.js.
Pro Tip: Always set the
Content-Type: application/json
header when sending JSON to ensure the server parses it correctly.
Common Pitfalls and Tips
- Invalid JSON: Check quotes, commas, and nesting. A small typo breaks the entire parse.
-
Date handling: JSON has no date type. Convert date strings back to
Date
objects afterparse
. - Large data: For huge JSON files, consider streaming parsers to avoid high memory usage.
- Security: Never parse JSON from untrusted sources without validation—malformed data can cause crashes.
Always validate your JSON schema if you accept user input. Libraries like AJV can help enforce structure and types.
Conclusion
JSON is the backbone of modern web communication. Its simple, text-based format makes it readable and cross-platform. Understanding the strict syntax rules, safe parsing methods, and Node.js file operations empowers you to work with data effectively. From basic REST API calls to complex config files, JSON keeps things consistent and interoperable.
Next time you send or receive data, you’ll know exactly how to structure it, avoid errors, and integrate with JavaScript code. Embrace JSON as your go-to data format, and your apps will be more reliable—and easier to maintain.
Top comments (0)