HomeCore API SkillsUnderstanding JSON & Data Formats
beginner10 min read· Module 5, Lesson 1

📋Understanding JSON & Data Formats

The language APIs speak — learn to read and write JSON

Understanding JSON & Data Formats

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight, text-based format for structuring and exchanging data between systems. Despite having "JavaScript" in its name, JSON is language-independent and is used by virtually every modern programming language.

Think of JSON as a universal language that computers use to talk to each other. When you send a message to an API or receive a response, that message is almost always formatted as JSON.


Why Does JSON Matter?

JSON is the backbone of modern web communication. Here is why you need to understand it:

  • APIs use JSON: When you call the Claude API, you send a JSON request and receive a JSON response. The same is true for almost every other API on the internet.
  • Configuration files: Many applications store their settings in JSON files (e.g., package.json, tsconfig.json).
  • Databases: NoSQL databases like MongoDB store data as JSON-like documents.
  • Data exchange: JSON is the standard format for sending data between a frontend application and a backend server.

Without understanding JSON, you cannot effectively work with APIs, configure tools, or build modern applications.


JSON Syntax Rules

JSON has simple but strict rules. Let us walk through each one.

1. Objects Use Curly Braces

A JSON object is a collection of key-value pairs wrapped in curly braces {}.

JSON
{ "name": "Alice", "age": 30 }

2. Arrays Use Square Brackets

A JSON array is an ordered list of values wrapped in square brackets [].

JSON
["apple", "banana", "cherry"]

3. Key-Value Pairs

Every piece of data in a JSON object is a key-value pair. The key is always a string in double quotes, followed by a colon, then the value.

JSON
{ "key": "value" }

4. Strings Must Use Double Quotes

JSON only allows double quotes for strings. Single quotes are NOT valid.

JSON
{ "correct": "This is valid", "also_correct": "Use double quotes only" }

5. Numbers Do Not Use Quotes

Numbers are written without quotes. They can be integers or decimals.

JSON
{ "integer": 42, "decimal": 3.14, "negative": -10 }

6. Booleans

JSON supports true and false as boolean values (lowercase, no quotes).

JSON
{ "is_active": true, "is_deleted": false }

7. Null

The special value null represents the absence of a value.

JSON
{ "middle_name": null }

Valid vs Invalid JSON — Common Mistakes

Many beginners make the same mistakes when writing JSON. Here are the most common ones.

Mistake 1: Trailing Commas

JSON does NOT allow a comma after the last item. This is invalid:

JSON
{ "name": "Alice", "age": 30, }

The correct version removes the trailing comma:

JSON
{ "name": "Alice", "age": 30 }

Mistake 2: Single Quotes

Single quotes are not valid in JSON:

JSON
{ 'name': 'Alice' }

You must use double quotes for both keys and string values.

Mistake 3: Unquoted Keys

Keys must always be quoted strings:

JSON
{ name: "Alice" }

This is valid JavaScript but NOT valid JSON. Keys need double quotes.

Mistake 4: Comments

JSON does NOT support comments. This is invalid:

JSON
{ "name": "Alice" // this is a comment }

If you need comments, consider using JSONC (JSON with Comments) or YAML.

Mistake 5: Using undefined

The value undefined does not exist in JSON. Use null instead.


Nested Objects

JSON objects can contain other objects. This is called nesting.

JSON
{ "user": { "name": "Alice", "address": { "street": "123 Main St", "city": "Springfield", "country": "US" }, "preferences": { "theme": "dark", "language": "en", "notifications": { "email": true, "sms": false } } } }

Nesting allows you to organize related data into logical groups. There is no limit to how deeply you can nest, but deeply nested structures become harder to read and maintain.


Arrays of Objects

One of the most common JSON patterns is an array of objects. APIs frequently return data in this format.

JSON
{ "products": [ { "id": 1, "name": "Laptop", "price": 999.99, "in_stock": true }, { "id": 2, "name": "Mouse", "price": 29.99, "in_stock": true }, { "id": 3, "name": "Monitor", "price": 449.00, "in_stock": false } ] }

Each element in the array is an object with the same structure. This is how databases typically return lists of records.


Reading a Real API Response — Claude's Response

When you send a request to the Claude API, you receive a JSON response. Here is what a real response looks like:

JSON
{ "id": "msg_01XFDUDYJgAACzvnptvVoYEL", "type": "message", "role": "assistant", "content": [ { "type": "text", "text": "Hello! How can I help you today?" } ], "model": "claude-sonnet-4-20250514", "stop_reason": "end_turn", "stop_sequence": null, "usage": { "input_tokens": 25, "output_tokens": 15 } }

Let us break this response down:

  • id: A unique identifier for this message.
  • type: The type of response (always "message" for chat).
  • role: Who generated the message ("assistant" means Claude).
  • content: An array of content blocks. Each block has a type and the actual text.
  • model: Which Claude model generated the response.
  • stop_reason: Why Claude stopped generating (e.g., it finished its turn).
  • stop_sequence: The stop sequence that was hit, if any (null means none).
  • usage: Token counts for billing — how many tokens were in the input and output.

Understanding this structure is essential for working with the Claude API.


JSON in JavaScript

JavaScript has two built-in methods for working with JSON.

JSON.parse() — Convert JSON String to Object

JavaScript
const jsonString = '{"name": "Alice", "age": 30}'; const user = JSON.parse(jsonString); console.log(user.name); // "Alice" console.log(user.age); // 30

JSON.stringify() — Convert Object to JSON String

JavaScript
const user = { name: "Alice", age: 30 }; const jsonString = JSON.stringify(user); console.log(jsonString); // '{"name":"Alice","age":30}'

Pretty Printing

You can format the output with indentation for readability:

JavaScript
const user = { name: "Alice", age: 30, hobbies: ["reading", "coding"] }; const pretty = JSON.stringify(user, null, 2); console.log(pretty); // { // "name": "Alice", // "age": 30, // "hobbies": [ // "reading", // "coding" // ] // }

Error Handling

Always wrap JSON.parse() in a try-catch block because invalid JSON will throw an error:

JavaScript
try { const data = JSON.parse("this is not json"); } catch (error) { console.error("Invalid JSON:", error.message); }

JSON in Python

Python uses the built-in json module.

json.loads() — Convert JSON String to Dictionary

Python
json_string = '{"name": "Alice", "age": 30}' user = json.loads(json_string) print(user["name"]) # Alice print(user["age"]) # 30

json.dumps() — Convert Dictionary to JSON String

Python
user = {"name": "Alice", "age": 30} json_string = json.dumps(user) print(json_string) # {"name": "Alice", "age": 30}

Pretty Printing in Python

Python
user = {"name": "Alice", "age": 30, "hobbies": ["reading", "coding"]} pretty = json.dumps(user, indent=2) print(pretty) # { # "name": "Alice", # "age": 30, # "hobbies": [ # "reading", # "coding" # ] # }

Reading and Writing JSON Files in Python

Python
# Writing JSON to a file data = {"name": "Alice", "scores": [95, 87, 92]} with open("data.json", "w") as f: json.dump(data, f, indent=2) # Reading JSON from a file with open("data.json", "r") as f: loaded = json.load(f) print(loaded["name"]) # Alice

Online Tools for JSON

When working with JSON, these tools will save you time:

JSONLint (jsonlint.com)

Paste your JSON into JSONLint and it will tell you whether it is valid. If there are errors, it highlights the exact line and explains the problem.

JSON Formatter

Many websites and browser extensions format (pretty-print) compressed JSON so you can read it more easily. Search for "JSON formatter" in your browser's extension store.

VS Code Built-in Formatter

If you use Visual Studio Code, you can format JSON files automatically:

  • Open a .json file
  • Press Shift + Alt + F (Windows/Linux) or Shift + Option + F (Mac)

jq — Command Line JSON Processor

For advanced users, jq is a powerful command-line tool for filtering and transforming JSON data:

Terminal
# Pretty print a JSON file cat data.json | jq '.' # Extract a specific field cat data.json | jq '.name' # Filter an array cat data.json | jq '.products[] | select(.price > 100)'

JSON vs XML vs YAML — A Brief Comparison

JSON is not the only data format. Here is how it compares to two other common formats.

JSON

JSON
{ "name": "Alice", "age": 30, "hobbies": ["reading", "coding"] }

Pros: Simple, widely supported, fast to parse. Cons: No comments, verbose for deeply nested data.

XML

XML
<person> <name>Alice</name> <age>30</age> <hobbies> <hobby>reading</hobby> <hobby>coding</hobby> </hobbies> </person>

Pros: Supports attributes, schemas, and namespaces. Cons: Very verbose, harder to read, slower to parse.

YAML

YAML
name: Alice age: 30 hobbies: - reading - coding

Pros: Human-readable, supports comments, compact. Cons: Indentation-sensitive (easy to break), less common in APIs.

When to Use Each

FormatBest For
JSONAPIs, web apps, configuration, data exchange
XMLLegacy systems, SOAP APIs, document formats
YAMLConfiguration files (Docker, K8s, CI/CD)

For API work and modern development, JSON is the default choice.


Practice Exercises

Now it is your turn. Try writing JSON for the following scenarios.

Exercise 1: A Person Object

Write a JSON object for a person with the following information:

  • Name: Bob
  • Age: 25
  • Email: bob@example.com
  • Is a student: true
  • Phone number: not available (null)

Solution:

JSON
{ "name": "Bob", "age": 25, "email": "bob@example.com", "is_student": true, "phone": null }

Exercise 2: A List of Products

Write a JSON array containing three products with id, name, price, and category.

Solution:

JSON
{ "products": [ { "id": 101, "name": "Wireless Headphones", "price": 79.99, "category": "electronics" }, { "id": 102, "name": "Coffee Mug", "price": 12.50, "category": "kitchen" }, { "id": 103, "name": "Running Shoes", "price": 120.00, "category": "sports" } ] }

Exercise 3: A Claude API Request

Write the JSON body for a request to the Claude API. You need:

  • model: claude-sonnet-4-20250514
  • max_tokens: 1024
  • A messages array with one user message: "What is JSON?"

Solution:

JSON
{ "model": "claude-sonnet-4-20250514", "max_tokens": 1024, "messages": [ { "role": "user", "content": "What is JSON?" } ] }

Key Takeaways

  1. JSON is a text-based data format used for exchanging data between systems.
  2. Objects use {}, arrays use [], strings use double quotes.
  3. Valid JSON is strict: no trailing commas, no single quotes, no comments.
  4. APIs communicate in JSON — understanding it is essential for API work.
  5. Every language has JSON tools: JSON.parse/stringify in JS, json.loads/dumps in Python.
  6. Use validators like JSONLint to catch errors quickly.
  7. Practice reading API responses — start with the Claude API response format.

JSON is a foundational skill. Once you are comfortable reading and writing JSON, every API and configuration file becomes much easier to work with.