JSON Syntax Basics
JSON is built on two structures:
1. Objects - A collection of key/value pairs enclosed in curly braces {}
2. Arrays - An ordered list of values enclosed in square brackets []
JSON Data Types:
- String: Text in double quotes -
"hello" - Number: Integer or decimal -
42,3.14 - Boolean:
trueorfalse - Null: Empty value -
null - Object: Nested structure -
{"key": "value"} - Array: List of values -
[1, 2, 3]
JSON Rules:
- Keys MUST be strings in double quotes
- No trailing commas allowed
- No comments allowed (unlike JavaScript)
- No single quotes (must use double quotes)
{
"name": "John Doe",
"age": 30,
"isActive": true,
"email": null,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["coding", "reading", "gaming"]
}JSON in JavaScript
JavaScript has built-in support for JSON with JSON.parse() and JSON.stringify():
// Parse JSON string to JavaScript object
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "John"
// Convert JavaScript object to JSON string
const user = { name: "Jane", age: 25 };
const json = JSON.stringify(user);
console.log(json); // '{"name":"Jane","age":25}'
// Pretty print with indentation
const prettyJson = JSON.stringify(user, null, 2);
console.log(prettyJson);
// {
// "name": "Jane",
// "age": 25
// }
// Fetch JSON from API
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data));
// Async/await syntax
async function getUsers() {
const response = await fetch('https://api.example.com/users');
const users = await response.json();
return users;
}JSON in Python
Python's json module provides JSON encoding and decoding:
import json
# Parse JSON string to Python dict
json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)
print(data["name"]) # "John"
# Convert Python dict to JSON string
user = {"name": "Jane", "age": 25}
json_str = json.dumps(user)
print(json_str) # '{"name": "Jane", "age": 25}'
# Pretty print with indentation
pretty_json = json.dumps(user, indent=2)
print(pretty_json)
# Read JSON from file
with open("data.json", "r") as f:
data = json.load(f)
# Write JSON to file
with open("output.json", "w") as f:
json.dump(user, f, indent=2)
# Handle special types
from datetime import datetime
def json_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
data = {"timestamp": datetime.now()}
json.dumps(data, default=json_serializer)JSON in Java
Java uses libraries like Jackson or Gson for JSON processing:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExample {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
// Parse JSON to Java object
String json = "{\"name\": \"John\", \"age\": 30}";
User user = mapper.readValue(json, User.class);
System.out.println(user.getName()); // "John"
// Convert Java object to JSON
User newUser = new User("Jane", 25);
String jsonOutput = mapper.writeValueAsString(newUser);
System.out.println(jsonOutput);
// Pretty print
String prettyJson = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(newUser);
// Read from file
User fromFile = mapper.readValue(new File("user.json"), User.class);
// Write to file
mapper.writeValue(new File("output.json"), newUser);
}
}
// POJO class
public class User {
private String name;
private int age;
// constructors, getters, setters
}JSON in Go
Go's encoding/json package provides JSON marshaling and unmarshaling:
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
// Parse JSON to struct
jsonStr := `{"name": "John", "age": 30}`
var user User
json.Unmarshal([]byte(jsonStr), &user)
fmt.Println(user.Name) // "John"
// Convert struct to JSON
newUser := User{Name: "Jane", Age: 25}
jsonBytes, _ := json.Marshal(newUser)
fmt.Println(string(jsonBytes))
// Pretty print with indentation
prettyJson, _ := json.MarshalIndent(newUser, "", " ")
fmt.Println(string(prettyJson))
}JSON vs XML vs YAML
| Feature | JSON | XML | YAML |
|---|---|---|---|
| Readability | Good | Verbose | Excellent |
| File Size | Compact | Large | Compact |
| Comments | No | Yes | Yes |
| Data Types | Basic | String only | Rich |
| Parsing Speed | Fast | Slower | Medium |
| Use Cases | APIs, Web | Documents, SOAP | Config files |
When to use JSON:
- REST APIs and web services
- JavaScript applications
- Data interchange between services
- Configuration (when comments aren't needed)
When to use YAML:
- Kubernetes and Docker configurations
- CI/CD pipelines (GitHub Actions, GitLab CI)
- Human-edited configuration files
When to use XML:
- Legacy systems and SOAP services
- Documents with mixed content
- When you need schemas (XSD)
Common JSON Errors
1. Trailing Commas
1// ❌ Invalid2{"name": "John", "age": 30,}34// ✅ Valid5{"name": "John", "age": 30}
2. Single Quotes
1// ❌ Invalid2{'name': 'John'}34// ✅ Valid5{"name": "John"}
3. Unquoted Keys
1// ❌ Invalid2{name: "John"}34// ✅ Valid5{"name": "John"}
4. Comments
1// ❌ Invalid - no comments in JSON2{3 "name": "John" // This is not allowed4}56// ✅ Valid - use a separate field for notes7{8 "_comment": "This is a workaround",9 "name": "John"10}
Frequently Asked Questions
What does JSON stand for?
JSON stands for JavaScript Object Notation. Despite the name, it's language-independent and used by virtually all programming languages.
Is JSON better than XML?
JSON is generally preferred for APIs and web applications due to its smaller size and faster parsing. XML is better for documents with mixed content or when you need features like comments and schemas.
Can JSON have comments?
No, standard JSON does not support comments. This is by design to keep the format simple. If you need comments, consider using JSON5 or YAML instead.
What's the maximum size of a JSON file?
There's no official limit, but practical limits depend on the parser and available memory. Most parsers handle files up to several gigabytes.
Is JSON case-sensitive?
Yes, JSON keys are case-sensitive. "Name" and "name" are different keys.