Chapters: JavaScript HTML & CSS JSON XML YAML ← Full TOC

← JSON Index

🔧 JSON Tools & Schema — jq, JSON Schema, JSON Pointer, and REST API patterns

Real-world JSON tooling includes jq for command-line processing, JSON Schema for validation, and standard patterns for REST APIs. These tools make JSON practical in production systems.

📋 Reference

ItemSyntax / ValueDescription
jq .jq '.' file.jsonPretty-print JSON file
jq .fieldjq '.name' file.jsonExtract a field value
jq .[]jq '.students[]' file.jsonIterate array elements
jq selectjq '.[] | select(.score > 90)'Filter array elements
jq mapjq '[.[] | {name, score}]'Map array to new shape
jq pipe |jq '.students | map(.name)'Chain operations
jq -rjq -r '.name'Raw output (no quotes around strings)
jq -cjq -c '.'Compact output (single line)
jq --argjq --arg n 'Alice' '.[] | select(.name == $n)'Pass variable into jq
jq lengthjq '.students | length'Array/object length
jq sort_byjq 'sort_by(.score) | reverse'Sort array by field
jq group_byjq 'group_by(.subject)'Group array by field value
jq keysjq 'keys'Return object keys as array
jq hasjq 'has("name")'True if object has key
jq typejq 'type'Return type of root value
JSON Schematype/properties/required/enum/patternValidate JSON structure
$schema"$schema": "https://json-schema.org/draft/2020-12/schema"JSON Schema version declaration
type"type": "object"|"array"|"string"|"number"|"boolean"|"null"Value type constraint
required"required": ["name", "email"]Required object properties
properties"properties": {"name": {"type": "string"}}Object property schemas
minimum/maximum"minimum": 0, "maximum": 100Numeric range constraints
minLength/maxLength"minLength": 1, "maxLength": 255String length constraints
pattern"pattern": "^[\\w.+-]+@[\\w-]+\\.[\\w.]+$"Regex pattern for strings
enum"enum": ["Math", "Science", "English"]Allowed values list
REST 200 GETGET /students → [{...},{...}]Collection endpoint
REST 201 POSTPOST /students {body} → {created object}Create resource
REST 204 DELETEDELETE /students/1 → (empty body)Delete resource
REST error{ "error": "Not found", "code": 404, "message": "..." }Error response shape

💡 Example

# ── jq command-line JSON processing ──────────────────────────
# Install: sudo apt install jq  /  brew install jq

# Sample file: students.json
cat > students.json << 'EOF'
[
  {"id":1,"name":"Alice","subject":"Math","score":95,"active":true},
  {"id":2,"name":"Bob",  "subject":"Science","score":87,"active":true},
  {"id":3,"name":"Carol","subject":"Math","score":92,"active":true},
  {"id":4,"name":"Dave", "subject":"Science","score":78,"active":false}
]
EOF

# Pretty-print
jq '.' students.json

# Extract names only
jq '[.[].name]' students.json

# Filter: score >= 90
jq '[.[] | select(.score >= 90)]' students.json

# Filter: active students only
jq '[.[] | select(.active == true)]' students.json

# Map to new shape
jq '[.[] | {name, grade: (if .score >= 90 then "A" else "B" end)}]' students.json

# Sort by score descending
jq 'sort_by(.score) | reverse' students.json

# Group by subject
jq 'group_by(.subject)' students.json

# Average score (requires reduce)
jq '(map(.score) | add) / length' students.json

# Extract value with variable
jq --arg name "Alice" '.[] | select(.name == $name)' students.json

# Count per subject
jq 'group_by(.subject) | map({subject: .[0].subject, count: length})' students.json

# ── JSON Schema validation (Python + jsonschema) ──────────────
# pip install jsonschema
import json, jsonschema

schema = {
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["name", "score", "email"],
  "properties": {
    "name":    {"type":"string","minLength":1,"maxLength":100},
    "score":   {"type":"number","minimum":0,"maximum":100},
    "email":   {"type":"string","pattern":"^[\\w.+-]+@[\\w-]+\\.[\\w.]+$"},
    "subject": {"type":"string","enum":["Math","Science","English","History"]}
  },
  "additionalProperties": False
}

valid   = {"name":"Alice","score":95,"email":"a@example.com","subject":"Math"}
invalid = {"name":"","score":110,"email":"not-an-email"}

for data in [valid, invalid]:
  try:
    jsonschema.validate(data, schema)
    print("✅ Valid:", data)
  except jsonschema.ValidationError as e:
    print("❌ Invalid:", e.message)

← JSON in Python  |  🏠 Index