Syntax at a Glance
| Type | Example | Remember |
|---|---|---|
| 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 |
| Number | 42, -3.14, 1.5e10 | No leading zeros, no NaN or Infinity |
| Boolean | true, false | Lowercase only |
| Null | null | Lowercase; 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
| Write | Means |
|---|---|
\" | Double quote |
\\ | Backslash (Windows paths: "C:\\Users\\Emily") |
\n, \r, \t | New line, carriage return, tab |
\b, \f | Backspace, form feed |
\/ | Slash (optional, / works too) |
\u00e9 | Any 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
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
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
$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)
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)
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
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
require "json" data = JSON.parse(text) # string keys data = JSON.parse(text, symbolize_names: true) # symbol keys text = JSON.pretty_generate(data)
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-JsonConvertTo-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
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
| Path | Selects |
|---|---|
$ | The whole document |
$.store.name | A key inside a key |
$.users[0] | The first item of an array |
$.users[-1] | The last item |
$.users[*].email | The email of every user |
$..price | Every 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
SELECT data->'user'->>'name' FROM events; -- -> keeps JSON, ->> gives text
SELECT * FROM events WHERE data @> '{"type": "click"}';
SELECT jsonb_pretty(data) FROM events;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
| Error | Usual cause | Fix |
|---|---|---|
| Unexpected token < | The server sent an HTML page, not JSON | Check the URL and the response status |
| Unexpected end of JSON input | Empty or cut-off response | Check for an empty body before parsing |
| Expected double-quoted property name | Trailing comma or single quotes | Remove the last comma, use " |
| Expecting value: line 1 column 1 | Python got empty text or HTML | Print the text before json.loads |
| Converting circular structure to JSON | An object refers to itself | Remove the loop or use a replacer |
| Object of type datetime is not JSON serializable | Python value JSON does not know | json.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
- JSONC / JSON5: JSON with comments and trailing commas, used for config files. See JSON Comments.
- JSON Lines (JSONL): one JSON object per line, for logs and large datasets. See JSON Lines.
- JSON Schema: describes what valid JSON looks like. See What Is JSON Schema?
- YAML, XML, CSV: compared in JSON vs YAML, JSON vs XML and JSON vs CSV.
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.