JSON (JavaScript Object Notation) is a lightweight text-based data exchange format that has become the de facto standard in modern web development. Despite the name containing the word "JavaScript", JSON is a language-independent format and is supported by almost all modern programming languages.
History of origin
JSON was developed by Douglas Crockford in the early 2000s as an alternative to XML for transmitting data between a browser and a server. Initially, the format was used in State Software projects, where Crocford worked as a consultant. The official JSON specification was published in 2006 as RFC 4627, and then updated in 2013 (RFC 7159) and 2017 (RFC 8259).
The simplicity and readability of JSON quickly made it a popular choice for web APIs. Today, JSON is used not only in web development, but also in configuration files, NoSQL databases, data exchange between microservices and many other areas.
Syntax basics
JSON is built on two universal data structures: objects (collections of key-value pairs) and arrays (ordered lists of values).
Data types
JSON supports the following data types:
Lines - sequences of Unicode characters enclosed in double quotes. Special characters are escaped with a backslash.
Numbers - integers or fractional numbers in the decimal number system. JSON does not distinguish between integers and floating-point numbers at the syntax level.
Boolean values — true or false.
Null — a special value indicating the absence of data.
Objects — unordered collections of key-value pairs, where keys are always strings.
Arrays — ordered lists of values of any type.
Structure example
{
"user": {
"id": 12345,
"username": "developer",
"email": "dev@example.com",
"isActive": true,
"roles": ["admin", "editor"],
"profile": {
"firstName": "Ivan",
"lastName": "Petrov",
"age": 28
},
"lastLogin": null
}
}Working with JSON in JavaScript
JavaScript provides a built-in JSON object with two main methods for working with this format.
Serialization: JSON.stringify()
The JSON.stringify() method converts a JavaScript object into a JSON string:
const user = {
name: "Alexey",
age: 30,
skills: ["JavaScript", "Vue.js", "Node.js"]
};
const jsonString = JSON.stringify(user);
// '{"name":"Alexey","age":30,"skills":["JavaScript","Vue.js","Node.js"]}'The method supports additional parameters for formatting control:
// Beautiful formatting with indents
const formatted = JSON.stringify(user, null, 2);
// Selective serialization of fields
const filtered = JSON.stringify(user, ['name', 'age']);
// Using the replacement function
const custom = JSON.stringify(user, (key, value) => {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value;
});Deserialization: JSON.parse()
The JSON.parse() method converts a JSON string back into a JavaScript object:
const jsonString = '{"name":"Alexey","age":30}'
const user = JSON.parse(jsonString);
console.log(user.name); // AlexeyYou can use the rewaver function to transform values when parsing:
const jsonWithDate = '{"created":"2024-01-15T10:30:00.000Z"}';
const data = JSON.parse(jsonWithDate, (key, value) => {
if (key === 'created') {
return new Date(value);
}
return value;
});
console.log(data.created instanceof Date); // true
Practical usage patterns
Deep copying of objects
JSON can be used for fast deep copying of objects, although this method has limitations:
const original = {
name: "Project",
data: { items: [1, 2, 3] }
};
const copy = JSON.parse(JSON.stringify(original));
copy.data.items.push(4);
console.log(original.data.items); // [1, 2, 3]
console.log(copy.data.items); // [1, 2, 3, 4]It is important to remember that this method does not copy functions, characters, undefined values and loses object prototypes.
Storing data in localStorage
JSON is ideal for serializing data before saving it to browser storage:
// Saving
const settings = {
theme: 'dark',
language: 'ru',
notifications: true
};
localStorage.setItem('settings', JSON.stringify(settings));
// Loading
const savedSettings = JSON.parse(localStorage.getItem('settings'));Working with the API
Modern APIs use JSON as the main data exchange format:
// Sending data to the server
async function createUser(userData) {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userData)
});
return await response.json();
}
// Use
const newUser = await createUser({
name: "Maria",
email: "maria@example.com"
});Common mistakes and their solutions
Cyclic links
JSON.stringify() throws an error if there are circular references:
const obj = { name: "test" };
obj.self = obj;
// TypeError: Converting circular structure to JSON
// JSON.stringify(obj);
// Solution using WeakSet
function stringifyWithCircular(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
return value;
});
}Invalid JSON
When working with external data sources, always use error handling:
function safeJsonParse(jsonString, fallback = null) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('JSON parsing error:', error.message);
return fallback;
}
}
const data = safeJsonParse(userInput, {});Loss of special data types
JSON does not support dates, regular expressions, and other special types:
const data = {
created: new Date(),
pattern: /test/gi
};
const json = JSON.stringify(data);
// {"created":"2024-11-21T10:00:00.000Z","pattern":{}}
// Solution: Create custom toJSON methods
data.created.toJSON = function() {
return { _type: 'Date', value: this.toISOString() };
};JSON Schema: Data Validation
JSON Schema is a dictionary for describing and validating the structure of JSON data:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
},
"email": {
"type": "string",
"format": "email"
}
},
"required": ["name", "email"]
}Using JSON Schema helps ensure data integrity in large applications and create API documentation.
Performance and optimization
When working with large amounts of data, it is important to consider the performance of JSON operations:
// Avoid multiple parsing
// Bad
for (let i = 0; i < 1000; i++) {
const data = JSON.parse(jsonString);
processData(data);
}
// Good
const data = JSON.parse(jsonString);
for (let i = 0; i < 1000; i++) {
processData(data);
}
// Use streaming for large files
async function processLargeJsonFile(url) {
const response = await fetch(url);
const reader = response.body.getReader();
const decoder = new TextDecoder();
// Processing in parts
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
// Chunk processing
}
}JSON security
JSON injection protection
When working with user input, it is important to avoid direct concatenation of strings:
// Not secure
const userInput = getUserInput();
const jsonString = '{"data":"' + userInput + '"}';
// Safe
const jsonString = JSON.stringify({ data: userInput });Validation of input data
Always validate data obtained from external sources:
function validateUserData(data) {
if (!data || typeof data !== 'object') {
throw new Error('Incorrect data format');
}
if (!data.name || typeof data.name !== 'string') {
throw new Error('Required name field is missing');
}
if (data.age && (typeof data.age !== 'number' || data.age < 0)) {
throw new Error('Invalid age value');
}
return true;
}Conclusion
JSON has become an integral part of modern development due to its simplicity, versatility, and broad support. Understanding the intricacies of working with this format, knowledge of common patterns and potential problems helps to create more reliable and productive applications. Whether you're working with APIs, configuration files, or local data storage, JSON remains a reliable tool for structured information exchange.
Do you want to deepen your knowledge of JavaScript and other web development technologies?
Join the educational platform Code, where you will find interactive courses in JavaScript, Python, HTML, CSS and other popular technologies. Kodik helps beginner developers learn programming through practical tasks and structured training.
Also join our Telegram channel, where you will receive support from experienced developers, you can discuss complex issues and be aware of the latest news from the world of development!
