Skip to Content

JSON Commands & Tools Cheatsheet

Table of Contents

  1. JSON Basics
  2. JSON Syntax Rules
  3. Data Types
  4. jq - Command Line JSON Processor
  5. Python JSON
  6. JavaScript JSON
  7. Node.js JSON
  8. Bash JSON Processing
  9. PowerShell JSON
  10. curl with JSON
  11. Common JSON Tools
  12. JSON Schema
  13. JSON Best Practices
  14. Interview Scenarios

JSON Basics

1. Basic JSON Structure

{ "name": "John Doe", "age": 30, "email": "john@example.com" }

2. Nested Objects

{ "user": { "name": "John Doe", "contact": { "email": "john@example.com", "phone": "123-456-7890" } } }

3. Arrays

{ "users": [ {"name": "John", "age": 30}, {"name": "Jane", "age": 25} ] }

4. Mixed Data Types

{ "string": "text", "number": 42, "float": 3.14, "boolean": true, "null": null, "array": [1, 2, 3], "object": {"key": "value"} }

JSON Syntax Rules

5. Valid JSON Must Have

  • Data in name/value pairs
  • Data separated by commas
  • Curly braces for objects
  • Square brackets [] for arrays
  • Double quotes "" for strings (not single quotes)
  • No trailing commas
  • No comments (standard JSON)

6. Escape Characters

{ "quote": "He said \"Hello\"", "backslash": "C:\\Windows\\System32", "newline": "Line 1\nLine 2", "tab": "Column1\tColumn2", "unicode": "\u00A9 Copyright" }

Data Types

7. String

{"name": "John Doe"}

8. Number

{ "integer": 42, "float": 3.14, "negative": -10, "scientific": 1.5e10 }

9. Boolean

{ "isActive": true, "isDeleted": false }

10. Null

{"middleName": null}

11. Array

{ "numbers": [1, 2, 3, 4, 5], "mixed": [1, "text", true, null, {"key": "value"}] }

12. Object

{ "person": { "firstName": "John", "lastName": "Doe" } }

jq - Command Line JSON Processor

13. Install jq

# macOS brew install jq # Ubuntu/Debian apt-get install jq # CentOS/RHEL yum install jq

14. Basic jq Usage

# Pretty print JSON echo '{"name":"John","age":30}' | jq '.' # From file jq '.' file.json # Compact output jq -c '.' file.json # Raw output (no quotes) jq -r '.name' file.json

15. Extract Field

# Single field echo '{"name":"John","age":30}' | jq '.name' # Output: "John" # Nested field echo '{"user":{"name":"John"}}' | jq '.user.name' # Output: "John"

16. Array Access

# First element echo '[1,2,3,4,5]' | jq '.[0]' # Output: 1 # Last element echo '[1,2,3,4,5]' | jq '.[-1]' # Output: 5 # Range echo '[1,2,3,4,5]' | jq '.[1:3]' # Output: [2,3] # All elements echo '[{"name":"John"},{"name":"Jane"}]' | jq '.[]'

17. Filter Arrays

# Filter by condition echo '[{"name":"John","age":30},{"name":"Jane","age":25}]' | jq '.[] | select(.age > 26)' # Get specific fields from array echo '[{"name":"John","age":30}]' | jq '.[] | {name, age}'

18. Map Operation

# Extract field from all array elements echo '[{"name":"John"},{"name":"Jane"}]' | jq '.[].name' # Or echo '[{"name":"John"},{"name":"Jane"}]' | jq 'map(.name)'

19. Create New Object

# Transform object echo '{"first":"John","last":"Doe"}' | jq '{name: (.first + " " + .last)}' # Output: {"name":"John Doe"}

20. Add/Modify Fields

# Add field echo '{"name":"John"}' | jq '. + {age: 30}' # Output: {"name":"John","age":30} # Update field echo '{"name":"John","age":30}' | jq '.age = 31'

21. Delete Fields

echo '{"name":"John","age":30,"email":"john@example.com"}' | jq 'del(.email)' # Output: {"name":"John","age":30}

22. Sort Arrays

echo '[{"name":"Charlie","age":35},{"name":"Alice","age":25}]' | jq 'sort_by(.age)' # Reverse sort echo '[3,1,4,1,5]' | jq 'sort | reverse'

23. Group By

echo '[{"dept":"IT","name":"John"},{"dept":"HR","name":"Jane"},{"dept":"IT","name":"Bob"}]' | jq 'group_by(.dept)'

24. Unique Values

echo '[1,2,2,3,3,3]' | jq 'unique' # Output: [1,2,3] echo '[{"name":"John"},{"name":"Jane"},{"name":"John"}]' | jq 'unique_by(.name)'

25. Length/Count

# Array length echo '[1,2,3,4,5]' | jq 'length' # Output: 5 # String length echo '"hello"' | jq 'length' # Output: 5 # Count items echo '[{"type":"A"},{"type":"B"},{"type":"A"}]' | jq '[.[] | select(.type=="A")] | length'

26. Keys

echo '{"name":"John","age":30,"email":"john@example.com"}' | jq 'keys' # Output: ["age","email","name"] # Unsorted keys echo '{"z":1,"a":2}' | jq 'keys_unsorted'

27. Has Key

echo '{"name":"John","age":30}' | jq 'has("name")' # Output: true

28. Type Checking

echo '{"name":"John","age":30}' | jq '.age | type' # Output: "number"

29. Conditional Logic

# if-then-else echo '{"age":30}' | jq 'if .age >= 18 then "Adult" else "Minor" end' # Multiple conditions echo '{"score":85}' | jq ' if .score >= 90 then "A" elif .score >= 80 then "B" else "C" end'

30. String Operations

# Concatenate echo '{"first":"John","last":"Doe"}' | jq '.first + " " + .last' # Convert to string echo '{"age":30}' | jq '.age | tostring' # Convert to number echo '{"age":"30"}' | jq '.age | tonumber' # Uppercase/Lowercase echo '"hello"' | jq 'ascii_upcase' echo '"HELLO"' | jq 'ascii_downcase' # Split string echo '"a,b,c"' | jq 'split(",")' # Join array echo '["a","b","c"]' | jq 'join(",")'

31. Math Operations

echo '{"price":100,"tax":0.08}' | jq '.price * (1 + .tax)' # Aggregate functions echo '[1,2,3,4,5]' | jq 'add' # Sum: 15 echo '[1,2,3,4,5]' | jq 'min' # 1 echo '[1,2,3,4,5]' | jq 'max' # 5

32. Merge Objects

echo '[{"a":1},{"b":2}]' | jq 'add' # Output: {"a":1,"b":2} # Recursive merge echo '{"a":{"x":1}}' | jq '. * {"a":{"y":2}}' # Output: {"a":{"x":1,"y":2}}

33. Flatten Arrays

echo '[[1,2],[3,4],[5]]' | jq 'flatten' # Output: [1,2,3,4,5] # Flatten one level echo '[[1,[2,3]],4]' | jq 'flatten(1)'

34. Advanced Filtering

# Any echo '[1,2,3,4,5]' | jq 'any(. > 3)' # Output: true # All echo '[1,2,3,4,5]' | jq 'all(. > 0)' # Output: true

35. Regular Expressions

# Test match echo '"hello@example.com"' | jq 'test("@")' # Find match echo '"Email: hello@example.com"' | jq 'match("([a-z]+)@([a-z.]+)") | .string' # Replace echo '"hello world"' | jq 'gsub("world"; "universe")'

36. Reduce

# Sum with reduce echo '[1,2,3,4,5]' | jq 'reduce .[] as $item (0; . + $item)'

37. Path Operations

# Get path to value echo '{"a":{"b":{"c":1}}}' | jq 'getpath(["a","b","c"])' # Set path echo '{}' | jq 'setpath(["a","b","c"]; 1)'

38. Stream Processing

# Process large JSON line by line cat large.json | jq -c '.[]' | while read line; do echo $line | jq '.field' done

39. Multiple Filters

# Pipe multiple operations echo '{"users":[{"name":"John","age":30},{"name":"Jane","age":25}]}' | \ jq '.users | map(select(.age > 26)) | .[].name'

40. Comments in jq

# jq doesn't support comments in filter expressions, but you can use: jq -f filter.jq input.json # filter.jq: # # This is a comment # .users[] | select(.active == true)

Python JSON

41. Import json Module

import json

42. Parse JSON String

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

43. Parse JSON File

with open('data.json', 'r') as file: data = json.load(file)

44. Convert to JSON String

data = {"name": "John", "age": 30} json_string = json.dumps(data) # Pretty print json_string = json.dumps(data, indent=2) # Sort keys json_string = json.dumps(data, indent=2, sort_keys=True)

45. Write JSON to File

data = {"name": "John", "age": 30} with open('output.json', 'w') as file: json.dump(data, file, indent=2)

46. Custom JSON Encoder

import json from datetime import datetime class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() return super().default(obj) data = {"timestamp": datetime.now()} json_string = json.dumps(data, cls=DateTimeEncoder)

47. Handle Non-serializable Objects

import json def json_default(obj): if isinstance(obj, set): return list(obj) raise TypeError data = {"items": {1, 2, 3}} json_string = json.dumps(data, default=json_default)

JavaScript JSON

48. Parse JSON

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

49. Stringify Object

const data = {name: "John", age: 30}; const jsonString = JSON.stringify(data); // Pretty print const formatted = JSON.stringify(data, null, 2);

50. Replacer Function

const data = {name: "John", age: 30, password: "secret"}; const json = JSON.stringify(data, (key, value) => { if (key === "password") return undefined; return value; });

51. Clone Object

const original = {name: "John", age: 30}; const clone = JSON.parse(JSON.stringify(original));

Node.js JSON

52. Read JSON File

const fs = require('fs'); // Synchronous const data = JSON.parse(fs.readFileSync('data.json', 'utf8')); // Asynchronous fs.readFile('data.json', 'utf8', (err, data) => { if (err) throw err; const jsonData = JSON.parse(data); }); // With require (for static files) const data = require('./data.json');

53. Write JSON File

const fs = require('fs'); const data = {name: "John", age: 30}; // Synchronous fs.writeFileSync('output.json', JSON.stringify(data, null, 2)); // Asynchronous fs.writeFile('output.json', JSON.stringify(data, null, 2), (err) => { if (err) throw err; console.log('Saved!'); });

Bash JSON Processing

54. Create JSON in Bash

cat > data.json << EOF { "name": "John", "age": 30 } EOF

55. Read JSON with jq in Bash

name=$(jq -r '.name' data.json) echo "Name: $name"

56. Iterate JSON Array

jq -r '.users[].name' data.json | while read name; do echo "User: $name" done

57. Build JSON Dynamically

# Using jq jq -n \ --arg name "John" \ --arg email "john@example.com" \ '{name: $name, email: $email}' # Using printf printf '{"name":"%s","age":%d}\n' "John" 30

PowerShell JSON

58. Parse JSON

$json = '{"name":"John","age":30}' $data = $json | ConvertFrom-Json $data.name

59. Read JSON File

$data = Get-Content data.json | ConvertFrom-Json

60. Convert to JSON

$object = @{ name = "John" age = 30 } $json = $object | ConvertTo-Json # Pretty print with depth $json = $object | ConvertTo-Json -Depth 10

61. Write JSON File

$object | ConvertTo-Json -Depth 10 | Out-File data.json

curl with JSON

62. GET Request

curl -X GET https://api.example.com/users curl -s https://api.example.com/users | jq '.'

63. POST JSON Data

curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d '{"name":"John","age":30}' # From file curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d @data.json

64. PUT Request

curl -X PUT https://api.example.com/users/1 \ -H "Content-Type: application/json" \ -d '{"name":"John Doe","age":31}'

65. DELETE Request

curl -X DELETE https://api.example.com/users/1 \ -H "Content-Type: application/json"

66. Authentication with JSON

# Bearer token curl -X GET https://api.example.com/users \ -H "Authorization: Bearer token123" \ -H "Content-Type: application/json" # Basic auth curl -X GET https://api.example.com/users \ -u username:password \ -H "Content-Type: application/json"

Common JSON Tools

67. Python json.tool

# Pretty print python -m json.tool input.json # Compact python -m json.tool --compact input.json # Sort keys python -m json.tool --sort-keys input.json

68. jsonlint (Validation)

npm install -g jsonlint jsonlint data.json jsonlint -q data.json # Quiet mode

69. json-server (Mock API)

npm install -g json-server json-server --watch db.json --port 3000

70. fx (Interactive Viewer)

npm install -g fx fx data.json cat data.json | fx

71. jid (Interactive Drill-down)

go install github.com/simeji/jid/cmd/jid@latest cat data.json | jid

72. gron (Make greppable)

brew install gron gron data.json gron data.json | grep "email" gron data.json | grep "email" | gron --ungron

JSON Schema

73. Basic Schema

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

74. Validate with ajv (Node.js)

const Ajv = require('ajv'); const ajv = new Ajv(); const schema = { type: "object", properties: { name: {type: "string"}, age: {type: "number"} }, required: ["name"] }; const data = {name: "John", age: 30}; const valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors);

75. Complex Schema Example

{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "user": { "type": "object", "properties": { "name": {"type": "string", "minLength": 1}, "email": {"type": "string", "format": "email"}, "age": {"type": "integer", "minimum": 0, "maximum": 120} }, "required": ["name", "email"] }, "tags": { "type": "array", "items": {"type": "string"}, "uniqueItems": true } }, "required": ["user"] }

JSON Best Practices

76. Naming Conventions

{ "camelCase": "preferred in JavaScript", "snake_case": "preferred in Python/Ruby", "kebab-case": "avoid in JSON keys" }

77. Date/Time Format

{ "createdAt": "2026-02-15T10:30:00Z", "timestamp": 1739629800, "date": "2026-02-15" }

78. Null vs Missing

{ "name": "John", "middleName": null, "age": 30 }

79. Consistent Structure

{ "success": true, "data": { "users": [] }, "error": null }

80. Pagination Structure

{ "data": [], "pagination": { "page": 1, "pageSize": 20, "totalPages": 5, "totalItems": 100 } }

Interview Scenarios

Scenario 1: Parse API Response

Question: Extract user emails from API response

# Sample response curl -s https://api.example.com/users | jq '.data[].email' # With filtering curl -s https://api.example.com/users | \ jq -r '.data[] | select(.active == true) | .email'

Scenario 2: Transform JSON Structure

Question: Convert array of objects to key-value pairs

# Input: [{"id":1,"name":"John"},{"id":2,"name":"Jane"}] # Output: {"1":"John","2":"Jane"} echo '[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]' | \ jq 'map({(.id|tostring): .name}) | add'

Scenario 3: Merge Multiple JSON Files

Question: Combine users from multiple JSON files

jq -s '.[0].users + .[1].users' file1.json file2.json # Or with reduce jq -s 'map(.users) | flatten' file1.json file2.json

Scenario 4: Extract Nested Values

Question: Get all product names from nested structure

{ "categories": [ { "name": "Electronics", "products": [ {"name": "Laptop", "price": 999}, {"name": "Phone", "price": 499} ] } ] }
jq '.categories[].products[].name' data.json # Or jq '[.categories[].products[].name]' data.json

Scenario 5: Group and Aggregate

Question: Group orders by customer and calculate total

echo '[ {"customer":"John","amount":100}, {"customer":"Jane","amount":200}, {"customer":"John","amount":150} ]' | jq 'group_by(.customer) | map({customer: .[0].customer, total: (map(.amount) | add)})'

Scenario 6: Filter by Date

Question: Get events from last 7 days

jq --arg date "$(date -u -d '7 days ago' +%Y-%m-%d)" \ '.events[] | select(.date >= $date)' events.json

Scenario 7: Validate JSON Structure

Question: Check if all users have required fields

jq 'all(.users[]; has("name") and has("email") and has("id"))' data.json

Scenario 8: Convert CSV to JSON

Question: Convert CSV file to JSON array

# Using jq jq -R -s ' split("\n") | map(split(",")) | .[1:] | map({name: .[0], age: .[1]}) ' data.csv # Python approach python3 << 'EOF' import csv, json with open('data.csv') as f: print(json.dumps(list(csv.DictReader(f)), indent=2)) EOF

Scenario 9: Update JSON Field

Question: Update user status in JSON file

# Update specific user jq '(.users[] | select(.id == 123) | .status) = "inactive"' data.json # Update all users jq '.users[].status = "active"' data.json # Save changes jq '(.users[] | select(.id == 123) | .status) = "inactive"' \ data.json > temp.json && mv temp.json data.json

Scenario 10: Build Configuration from Template

Question: Generate config JSON from environment variables

#!/bin/bash cat > config.json << EOF { "database": { "host": "${DB_HOST:-localhost}", "port": ${DB_PORT:-5432}, "name": "${DB_NAME:-mydb}" }, "app": { "port": ${APP_PORT:-3000}, "env": "${APP_ENV:-development}" } } EOF # Validate jq '.' config.json

Scenario 11: Extract Error Messages

Question: Parse error logs and extract unique error messages

jq -r '.logs[] | select(.level == "error") | .message' app.log.json | \ sort | uniq -c | sort -rn

Scenario 12: Create Backup with Metadata

Question: Add backup metadata to JSON

jq '. + { backup: { timestamp: now | strftime("%Y-%m-%d %H:%M:%S"), version: "1.0" } }' data.json > backup.json

Scenario 13: Diff Two JSON Files

Question: Find differences between two JSON files

# Using jq diff <(jq -S '.' file1.json) <(jq -S '.' file2.json) # Using Python python3 << 'EOF' import json, sys with open('file1.json') as f1, open('file2.json') as f2: data1, data2 = json.load(f1), json.load(f2) def find_diff(d1, d2, path=""): for key in set(list(d1.keys()) + list(d2.keys())): if key not in d2: print(f"Removed: {path}.{key}") elif key not in d1: print(f"Added: {path}.{key}") elif d1[key] != d2[key]: print(f"Changed: {path}.{key}: {d1[key]} -> {d2[key]}") find_diff(data1, data2) EOF

Scenario 14: Flatten Nested JSON

Question: Flatten all nested objects to single level

jq 'to_entries | map({(.key): .value}) | add' nested.json # Python approach for complex nesting python3 << 'EOF' import json def flatten(d, parent_key='', sep='_'): items = [] for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.extend(flatten(v, new_key, sep=sep).items()) else: items.append((new_key, v)) return dict(items) with open('nested.json') as f: data = json.load(f) print(json.dumps(flatten(data), indent=2)) EOF

Scenario 15: Generate Test Data

Question: Create mock JSON data for testing

# Using jq jq -n '[range(1;11) | { id: ., name: "User\(.)", email: "user\(.)@example.com", active: (. % 2 == 0) }]' # Using Python python3 << 'EOF' import json from faker import Faker fake = Faker() users = [ { "id": i, "name": fake.name(), "email": fake.email(), "phone": fake.phone_number(), "address": fake.address() } for i in range(1, 11) ] print(json.dumps(users, indent=2)) EOF

Advanced Tips

81. Streaming Large JSON Files

# Don't load entire file into memory jq -c '.[]' large.json | while read item; do echo "$item" | jq '.field' done

82. Conditional Output

# Output name if age > 30, otherwise email jq '.users[] | if .age > 30 then .name else .email end' data.json

83. Calculate Percentage

# Calculate percentage of active users jq ' (.users | map(select(.active)) | length) as $active | (.users | length) as $total | ($active / $total * 100) ' data.json

84. Format Numbers

# Format with 2 decimal places echo '{"price":99.999}' | jq '.price | . * 100 | round / 100'

85. Environment Variables in jq

export USER_ID=123 jq --arg uid "$USER_ID" '.users[] | select(.id == ($uid|tonumber))' data.json

Quick Reference

jq Common Filters

. Current object .field Access field .[n] Array index .[] All array elements .[n:m] Array slice | Pipe , Multiple outputs ? Optional operator // Alternative operator select() Filter map() Transform array length Length keys Object keys sort_by() Sort group_by() Group unique Unique values add Sum/merge min/max Min/Max values

JSON Validation Tools

jq Command-line processor jsonlint Validator ajv Schema validator fx Interactive viewer gron Make greppable

Last updated on