DEV Community

Cover image for What is JSON?
Marie Berezhna
Marie Berezhna

Posted on

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is commonly used in web development for transmitting data between a server and a client. Despite its name, JSON is language-independent and widely supported across programming languages.

JSON Structure

At its core, JSON is built on two data structures:

Key-Value Pairs (Objects): Represented as key-value pairs enclosed in curly braces {}.

{
  "name": "John",
  "age": 30,
  "isDeveloper": true
}
Enter fullscreen mode Exit fullscreen mode

Ordered Lists (Arrays): Represented as a list of values enclosed in square brackets [].

["apple", "banana", "cherry"]
Enter fullscreen mode Exit fullscreen mode

Common Use Cases

  • APIs: Exchanging data between a client and a server.
  • Configuration Files: Storing settings for applications.
  • Data Storage: Simple, flat data storage for small projects.

Parsing and Stringifying JSON

In JavaScript, you can convert JSON strings to objects using JSON.parse() and convert objects to JSON strings using JSON.stringify():

const jsonString = '{"name":"Alice","age":25}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Output: Alice

const objectData = { city: "Paris", country: "France" };
const stringifiedData = JSON.stringify(objectData);
console.log(stringifiedData); // Output: {"city":"Paris","country":"France"}
Enter fullscreen mode Exit fullscreen mode

Benefits of JSON

  • Human-Readable: Easy to read and write.
  • Lightweight: Minimal syntax for efficient data exchange.
  • Language-Independent: Supported by most modern programming languages.

Alternatives to JSON

While JSON is widely used, there are several alternatives that serve similar purposes, each with its own advantages:

1. XML (eXtensible Markup Language):
More verbose than JSON.
Supports attributes and mixed content.
Commonly used in legacy systems and document storage.

2. YAML (YAML Ain't Markup Language):
More human-readable than JSON.
Often used in configuration files (e.g., Docker Compose, Kubernetes).
Supports comments and anchors for reusing content.

3. MessagePack:
Binary format that is more compact than JSON.
Suitable for scenarios where bandwidth is limited.

4. Protobuf (Protocol Buffers):
A compact binary format developed by Google.
Requires schema definitions.
Commonly used for high-performance communication between services.

5. CBOR (Concise Binary Object Representation):
A binary format designed for small code and message size.
Useful in IoT and constrained environments.

6. Avro:
A data serialization system developed by Apache.
Integrates schema definitions with data.
Commonly used in big data pipelines.

Things You Might Not Know About JSON

JSON is Not Exclusive to JavaScript
Despite its name, JSON is not limited to JavaScript. Many languages, such as Python, Java, and Ruby, have built-in libraries for handling JSON.

Comments Are Not Allowed in JSON
JSON does not support comments for compatibility reasons. If you need comments, consider using alternatives like JSON5 or adding metadata within the JSON object.

{
  "data": "value",
  "_comment": "This is a workaround for comments."
}
Enter fullscreen mode Exit fullscreen mode

JSON5 Adds Useful Enhancements
JSON5 is an extension of JSON that allows for features like trailing commas, single quotes, and comments, making it more developer-friendly.

{
  name: 'Jane', // Single quotes and comments
  age: 28,
}
Enter fullscreen mode Exit fullscreen mode

Handling Circular References
JSON cannot handle circular references directly, as it will throw a "TypeError: Converting circular structure to JSON." Libraries like circular-json or flatted can help address this issue.

The replacer and reviver Parameters in JSON Methods

  • JSON.stringify() accepts a replacer parameter to filter or transform values during serialization.
  • JSON.parse() accepts a reviver parameter to transform values during parsing.
const data = { name: "Eve", age: 40, password: "secret" };
const filteredJSON = JSON.stringify(data, (key, value) => key === "password" ? undefined : value);
console.log(filteredJSON); // Output: {"name":"Eve","age":40}
Enter fullscreen mode Exit fullscreen mode

JSON is Case-Sensitive
Keys and values in JSON are case-sensitive, which can lead to subtle bugs if not handled carefully.

JSON Schema for Validation
JSON Schema is a powerful tool for validating the structure of JSON data. It ensures data integrity and helps in API development.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "required": ["name", "age"]
}
Enter fullscreen mode Exit fullscreen mode

JSON's Relationship to YAML
YAML (YAML Ain't Markup Language) is often used as an alternative to JSON in configuration files. While YAML is more human-readable, JSON is less error-prone due to its stricter syntax.

Conclusion

JSON remains a top choice for its simplicity, readability, and widespread adoption. Whether you stick with JSON or explore alternatives, understanding their differences can help you choose the best tool for your specific use case.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay