How can I catch new posts?
Bookmark this blog and watch the homepage and tools hub—we surface new guides there. No account or mailing list is required to read articles.
Master JSON syntax rules, data types, and practical JSON operations in JavaScript and Python. Learn why JSON is the standard for modern Web APIs.
JSON (JavaScript Object Notation) is a lightweight data storage and interchange format. The core design philosophy of JSON is to make data both human-readable and machine-parseable, a dual characteristic that has made it one of the most important data exchange formats in modern web development.
JSON originated from the JavaScript language, but it has evolved into a data format standard that is completely independent of programming languages. Almost all modern programming languages—whether Python, Java, PHP, or Ruby—natively support reading and generating JSON. This cross-platform compatibility makes JSON the preferred format for data transmission between servers and clients, as well as between different systems.
JSON uses plain text format, meaning it can be transmitted and stored in any environment that supports text processing, without relying on specific software or platforms.
JSON's "lightweight" characteristic is reflected in two aspects: first, its syntax structure is extremely concise, containing no redundant markup or formatting requirements; second, JSON files are typically 30%-50% smaller than equivalent XML files, significantly reducing network overhead and loading time in web applications that need to frequently transmit large amounts of data.
JSON's syntax design follows strict rules that ensure data format consistency and parseability. Understanding these basic rules is the foundation for using JSON correctly.
"name": "John"{} are used to wrap objects, representing an unordered collection of key-value pairs[] are used to wrap arrays, representing an ordered list of valuesIn actual development, developers often encounter common errors related to JSON format. Here are the "pitfalls" you need to watch out for:
1. JSON does not support commentsThe JSON specification explicitly does not support comments of any kind. If you add // or /* */ style comments to a JSON file, the parser will directly report an error. If you need to include explanatory information in JSON, consider adding a special key like "_comment": "This is explanatory text", but this practice is not recommended for production environments.
This is an extremely common mistake. In JavaScript, you can use either single or double quotes to define strings, but in JSON, all strings must use double quotes. For example, {'name': 'John'} is invalid JSON and must be written as {"name": "John"}.
In JavaScript, you can have an optional trailing comma after the last element of an object or array, but this is strictly prohibited in JSON. {"name": "John",} will cause a parsing error; the correct format is {"name": "John"}.
In JSON, all keys must be of string type and must be wrapped in double quotes. A notation like {age: 25} is valid in JavaScript but invalid in JSON; it must be written as {"age": 25}.
JSON supports six core data types, each with its own specific syntax rules and purposes. Understanding these data types is key to correctly constructing JSON data structures.
Strings are the most commonly used data type in JSON, used to represent textual information. Strings must be wrapped in double quotes and can contain any Unicode characters. JSON strings support common escape characters such as \n (newline), \t (tab), \" (double quote), etc.
{
"name": "Zhang San",
"email": "zhangsan@example.com",
"address": "88 Jianguo Road\nChaoyang District, Beijing"
}The Number type in JSON includes integers and floating-point numbers, but does not support octal or hexadecimal formats. Numbers can be positive, negative, contain decimal parts, or be expressed using scientific notation.
{
"age": 28,
"price": 99.99,
"temperature": -5,
"largeNumber": 3.14e10
}Objects are unordered collections of key-value pairs, wrapped in curly braces. The key in each key-value pair must be a string, and the value can be any valid JSON data type. Objects can be nested to form complex data structures.
{
"user": {
"profile": {
"name": "Li Si",
"age": 32
},
"preferences": {
"theme": "dark",
"language": "en-US"
}
}
}Arrays are ordered lists of values, wrapped in square brackets. Values in an array can be of any JSON data type, including mixed types. Arrays are particularly suitable for representing collections of data, such as user lists or tags.
{
"users": ["Alice", "Bob", "Charlie"],
"scores": [95, 87, 92, 88],
"mixed": [1, "two", true, null]
}Boolean values can only be true or false. Note that these values are lowercase and do not need to be wrapped in quotes.
{
"isActive": true,
"hasPermission": false,
"isPremium": true
}null represents an empty or nonexistent value. It also does not require quotes and must be lowercase.
{
"middleName": null,
"avatar": null,
"lastLoginTime": null
}JSON and XML are both formats for data storage and transmission, but they have significant differences in design philosophy, syntax structure, and usage scenarios. The following comparison table helps you quickly understand the differences:
| Feature | JSON | XML |
|---|---|---|
| Full Name | JavaScript Object Notation | eXtensible Markup Language |
| File Size | Smaller, typically 30-50% smaller than XML | Larger, requires closing tags |
| Readability | Concise and clear, easy to read | Clear structure but verbose |
| Parsing Speed | Faster, can be parsed using standard functions | Slower, requires XML parser |
| Data Types | Supports multiple native data types | Text only, requires custom type definition |
| Array Support | Natively supports arrays | Does not support array concept |
| Comments | Does not support comments | Supports comments |
| Namespaces | Does not support namespaces | Supports namespaces |
| Use Cases | Web APIs, mobile applications, configuration files | Enterprise documents, complex data structures |
Recommendation: For modern web development and mobile applications, JSON is typically the better choice because it is lighter, parses faster, and has better native compatibility with JavaScript. XML is more suitable for enterprise application scenarios that require complex document structures, namespace support, or strict validation.
In actual development, the most common JSON operations are converting JSON strings into program objects, and converting objects into JSON strings. Here are the specific implementation methods in JavaScript and Python.
JavaScript provides two core methods for handling JSON data: JSON.parse() and JSON.stringify().
// JSON string
const jsonString = '{"name": "Zhang San", "age": 28, "city": "Beijing"}';
// Parse into JavaScript object
const obj = JSON.parse(jsonString);
// Use the parsed object
console.log(obj.name); // Output: Zhang San
console.log(obj.age); // Output: 28
// Handle nested structures
const complexJson = `{
"user": {
"profile": {"name": "Li Si"},
"skills": ["JavaScript", "Python"]
}
}`;
const data = JSON.parse(complexJson);
console.log(data.user.profile.name); // Output: Li Si
console.log(data.user.skills[0]); // Output: JavaScript2. JSON.stringify() - Convert JavaScript object to JSON string// JavaScript object
const user = {
name: "Wang Wu",
age: 32,
email: "wangwu@example.com",
isActive: true
};
// Convert to JSON string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// Output: {"name":"Wang Wu","age":32,"email":"wangwu@example.com","isActive":true}
// Formatted output (with indentation)
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
/* Output:
{
"name": "Wang Wu",
"age": 32,
"email": "wangwu@example.com",
"isActive": true
}
*/
// Include only specific properties
const filtered = JSON.stringify(user, ["name", "email"], 2);
console.log(filtered);
/* Output:
{
"name": "Wang Wu",
"email": "wangwu@example.com"
}
*/Python has a built-in json module that provides functionality similar to JavaScript.
import json
# JSON string
json_string = '{"name": "Zhang San", "age": 28, "city": "Beijing"}'
# Parse into Python dictionary
data = json.loads(json_string)
# Use the parsed data
print(data['name']) # Output: Zhang San
print(data['age']) # Output: 28
# Handle nested structures
complex_json = '''
{
"user": {
"profile": {"name": "Li Si"},
"skills": ["JavaScript", "Python"]
}
}
'''
data = json.loads(complex_json)
print(data['user']['profile']['name']) # Output: Li Si
print(data['user']['skills'][0]) # Output: JavaScript2. json.dumps() - Convert Python object to JSON stringimport json
# Python dictionary
user = {
"name": "Wang Wu",
"age": 32,
"email": "wangwu@example.com",
"is_active": True,
"skills": ["Python", "JavaScript", "Go"]
}
# Convert to JSON string
json_string = json.dumps(user)
print(json_string)
# Output: {"name": "Wang Wu", "age": 32, "email": "wangwu@example.com", ...}
# Formatted output (with indentation)
pretty_json = json.dumps(user, indent=2, ensure_ascii=False)
print(pretty_json)
""" Output:
{
"name": "Wang Wu",
"age": 32,
"email": "wangwu@example.com",
"is_active": true,
"skills": [
"Python",
"JavaScript",
"Go"
]
}
"""
# Sort keys
sorted_json = json.dumps(user, sort_keys=True, indent=2)
print(sorted_json)According to analyses from Oracle and DigitalOcean, JSON plays an irreplaceable role in modern software development:
API Communication: Almost all modern RESTful APIs use JSON as their data exchange format because it is lightweight, easy to parse, and natively compatible with JavaScript.Database Storage: NoSQL databases (such as MongoDB, Couchbase) natively support JSON format storage, and mainstream relational databases (such as Oracle, PostgreSQL, MySQL) have also begun offering JSON data type support, allowing developers to flexibly store and query JSON data within relational databases.Configuration Files: More and more applications and development tools are adopting JSON as their configuration file format, including package.json (Node.js), tsconfig.json (TypeScript), .vscode/settings.json (VS Code), and others. This is because JSON's conciseness and readability are superior to traditional INI or XML formats.Dedicated to providing developers with the best JSON processing tools
More posts coming soon...
Back to BlogFollowing the blog, topics we cover, and how to suggest guides.
Bookmark this blog and watch the homepage and tools hub—we surface new guides there. No account or mailing list is required to read articles.
JSON validation, formatting, conversion, debugging workflows, and JSON Work releases—mapped to what the free on-site tools can do locally in your browser.
Yes. Reach out via the About page or GitHub; we prioritize guides tied to real integration and debugging scenarios.