Syntax at a Glance

TypeExampleRemember
Object{"name": "Emily", "age": 30}Keys must be strings in double quotes
Array[1, "two", true]Items can have different types
String"hello"Double quotes only, never single
Number42, -3.14, 1.5e10No leading zeros, no NaN or Infinity
Booleantrue, falseLowercase only
NullnullLowercase; there is no undefined

Not allowed: trailing commas, comments, single quotes, unquoted keys, and values like undefined, NaN or functions. The full rules with examples are in JSON Syntax Rules.

Escape Sequences in Strings

WriteMeans
\"Double quote
\\Backslash (Windows paths: "C:\\Users\\Emily")
\n, \r, \tNew line, carriage return, tab
\b, \fBackspace, form feed
\/Slash (optional, / works too)
\u00e9Any Unicode character by its hex code (here é)

Any other backslash, like \d or a single \ in a path, is an error: see Bad Escaped Character in JSON. To escape a whole text, use JSON Escape.

Parse and Write JSON in Every Language

"Parse" turns JSON text into data; "stringify" or "dump" turns data into JSON text.

JavaScript

JavaScript
const data = JSON.parse('{"name": "Emily", "age": 30}')
data.name                          // "Emily"
JSON.stringify(data)               // '{"name":"Emily","age":30}'
JSON.stringify(data, null, 2)      // pretty, 2 spaces

// fetch
const res = await fetch(url)
const json = await res.json()

JSON.stringify drops undefined and functions, writes NaN as null and dates as ISO strings. More in JSON.parse in JavaScript and JSON in TypeScript.

Python

Python
import json

data = json.loads('{"name": "Emily", "age": 30}')   # str → dict
text = json.dumps(data, indent=2)                    # dict → str
text = json.dumps(data, ensure_ascii=False)          # keep ü, é, 日本 as they are

with open("data.json", encoding="utf-8") as f:       # file → dict
    data = json.load(f)
with open("out.json", "w", encoding="utf-8") as f:   # dict → file
    json.dump(data, f, indent=2)

Full guide: JSON in Python. Errors: JSONDecodeError and Object is not JSON serializable.

PHP

PHP
$data = json_decode($text, true);              // true → associative array
$text = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$data = json_decode($text, true, 512, JSON_THROW_ON_ERROR);   // throw instead of returning null

Java (Jackson)

Java
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(text, User.class);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
JsonNode node = mapper.readTree(text);          // no class needed
String name = node.get("name").asText();

C# (System.Text.Json)

C#
using System.Text.Json;

var user = JsonSerializer.Deserialize<User>(text);
var json = JsonSerializer.Serialize(user, new JsonSerializerOptions { WriteIndented = true });
using var doc = JsonDocument.Parse(text);       // no class needed
var name = doc.RootElement.GetProperty("name").GetString();

Go

Go
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

var u User
err := json.Unmarshal([]byte(text), &u)
out, err := json.MarshalIndent(u, "", "  ")

Ruby

Ruby
require "json"

data = JSON.parse(text)                          # string keys
data = JSON.parse(text, symbolize_names: true)   # symbol keys
text = JSON.pretty_generate(data)

PowerShell

PowerShell
$data = '{"name": "Emily", "age": 30}' | ConvertFrom-Json
$data.name                                  # Emily
$data | ConvertTo-Json -Depth 10            # always set -Depth for nested data
Get-Content data.json -Raw | ConvertFrom-Json

ConvertTo-Json only goes 2 levels deep by default. More in JSON in PowerShell.

Want classes instead of maps? Generate them from an example with JSON to Java, C#, Go, Python, Ruby or TypeScript.

Command Line

Shell
jq . data.json                      # pretty print
jq -c . data.json                   # minify to one line
jq '.users[0].name' data.json       # get a value
jq -r '.users[].email' data.json    # every email, without quotes
jq '.users | length' data.json      # count items
jq '.users[] | select(.age > 30)' data.json   # filter

python -m json.tool data.json       # pretty print without installing jq

curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Emily"}'

Sending JSON from the terminal, including Windows quoting: Send JSON with curl.

JSONPath Quick Reference

PathSelects
$The whole document
$.store.nameA key inside a key
$.users[0]The first item of an array
$.users[-1]The last item
$.users[*].emailThe email of every user
$..priceEvery price at any depth
$.users[?(@.age > 30)]Users older than 30
$["first name"]A key with spaces or symbols

Try any path on your own JSON in the JSONPath Tester.

JSON in SQL

PostgreSQL (jsonb)
SELECT data->'user'->>'name' FROM events;          -- -> keeps JSON, ->> gives text
SELECT * FROM events WHERE data @> '{"type": "click"}';
SELECT jsonb_pretty(data) FROM events;
MySQL 8
SELECT data->>'$.user.name' FROM events;           -- same as JSON_UNQUOTE(JSON_EXTRACT(...))
SELECT * FROM events WHERE JSON_EXTRACT(data, '$.type') = 'click';

Loading a JSON file into a table: Import JSON into a Database, or generate statements with JSON to SQL.

Common Errors and Quick Fixes

ErrorUsual causeFix
Unexpected token <The server sent an HTML page, not JSONCheck the URL and the response status
Unexpected end of JSON inputEmpty or cut-off responseCheck for an empty body before parsing
Expected double-quoted property nameTrailing comma or single quotesRemove the last comma, use "
Expecting value: line 1 column 1Python got empty text or HTMLPrint the text before json.loads
Converting circular structure to JSONAn object refers to itselfRemove the loop or use a replacer
Object of type datetime is not JSON serializablePython value JSON does not knowjson.dumps(data, default=str)

Paste broken JSON into the JSON Repair tool to fix trailing commas, single quotes and comments automatically, or into the JSON Validator to see the exact line of each error.

Related Formats

Frequently Asked Questions

What is a JSON cheat sheet?

A one-page reference with the JSON syntax, escape sequences and the code to read and write JSON in common languages, so you do not have to search for each detail.

How do I parse JSON in different languages?

JavaScript uses JSON.parse, Python json.loads, PHP json_decode, Java Jackson's ObjectMapper.readValue, C# JsonSerializer.Deserialize, Go json.Unmarshal, Ruby JSON.parse and PowerShell ConvertFrom-Json.

Which characters must be escaped in JSON?

Inside strings, the double quote and backslash must be escaped as \" and \\, and control characters such as line breaks and tabs as \n and \t. Any character can also be written as \u followed by four hex digits.

How do I pretty print JSON quickly?

Use JSON.stringify(data, null, 2) in JavaScript, json.dumps(data, indent=2) in Python, jq . file.json on the command line, or paste it into an online JSON formatter.

Related Tools