Tutorial

What is JSON?

Master JSON syntax rules, data types, and practical JSON operations in JavaScript and Python. Learn why JSON is the standard for modern Web APIs.

2026-04-015 min read

What is JSON?

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 Syntax Rules

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.

Basic Syntax Structure

  • Key-Value Pair Format: JSON data consists of name/value pairs, with each pair separated by a colon, e.g., "name": "John"
  • Double Quote Requirement: All key names must be wrapped in double quotes—an important difference between JSON and JavaScript objects
  • Data Separators: Multiple key-value pairs are separated by commas, but no comma is allowed after the last pair
  • Object Container: Curly braces {} are used to wrap objects, representing an unordered collection of key-value pairs
  • Array Container: Square brackets [] are used to wrap arrays, representing an ordered list of values
  • Nested Structures: Objects and arrays can be nested within each other to form complex data hierarchies

Common JSON Mistakes

In 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 comments

The 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.

2. Must use double quotes, cannot use single quotes

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"}.

3. No trailing comma after the last element

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"}.

4. Key names must be strings

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}.

Core Data Types

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.

String

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"
}

Number

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
}

Object

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"
    }
  }
}

Array

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

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

null represents an empty or nonexistent value. It also does not require quotes and must be lowercase.

{
  "middleName": null,
  "avatar": null,
  "lastLoginTime": null
}

JSON vs XML

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:

FeatureJSONXML
Full NameJavaScript Object NotationeXtensible Markup Language
File SizeSmaller, typically 30-50% smaller than XMLLarger, requires closing tags
ReadabilityConcise and clear, easy to readClear structure but verbose
Parsing SpeedFaster, can be parsed using standard functionsSlower, requires XML parser
Data TypesSupports multiple native data typesText only, requires custom type definition
Array SupportNatively supports arraysDoes not support array concept
CommentsDoes not support commentsSupports comments
NamespacesDoes not support namespacesSupports namespaces
Use CasesWeb APIs, mobile applications, configuration filesEnterprise 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.

Hands-on: How to Work with JSON in JS/Python?

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.

JSON Operations in JavaScript

JavaScript provides two core methods for handling JSON data: JSON.parse() and JSON.stringify().

1. JSON.parse() - Convert JSON string to JavaScript object

// 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: JavaScript

2. 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"
}
*/

JSON Operations in Python

Python has a built-in json module that provides functionality similar to JavaScript.

1. json.loads() - Convert JSON string to Python object

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: JavaScript

2. json.dumps() - Convert Python object to JSON string

import 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)

The Importance of JSON in Modern Development

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.


Continue Using JSON Tools

JSON Work Team

Dedicated to providing developers with the best JSON processing tools

Related Posts

More posts coming soon...

Back to Blog

Related tools

Frequently Asked Questions

Following the blog, topics we cover, and how to suggest guides.

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.

What do you write about?

JSON validation, formatting, conversion, debugging workflows, and JSON Work releases—mapped to what the free on-site tools can do locally in your browser.

Can I suggest a tutorial topic?

Yes. Reach out via the About page or GitHub; we prioritize guides tied to real integration and debugging scenarios.

Need Help?