JSON in Ruby
Parse and generate JSON data in Ruby using the standard json library, including nested objects, pretty printing, and symbol key conversion.
Introduction to JSON
JSON (JavaScript Object Notation) is the standard data interchange format for APIs and config files. Ruby's built-in `json` library provides `JSON.generate` and `JSON.parse`.
1. What Is JSON?
JSON is a text format made of key-value pairs, arrays, and primitive values.
JSON Data Types
JSON supports six data types: String, Number, Boolean, Null, Object (key-value), and Array. Ruby types map to these when serializing.
1. Ruby ↔ JSON Type Mapping
Each Ruby type maps to a corresponding JSON type.
JSON Syntax Rules
JSON has strict syntax rules: keys must be double-quoted strings, no trailing commas, no comments, and no undefined/function values.
1. Valid vs Invalid JSON
Common mistakes that make JSON invalid.
Converting Ruby to JSON (Serialization)
`JSON.generate` converts Ruby objects to JSON strings. `JSON.pretty_generate` formats with indentation for human readability.
1. JSON.generate
Converts Ruby Hash/Array to a compact JSON string.
2. JSON.pretty_generate
Formats JSON with indentation for readability.
3. .to_json
Any Ruby Hash or Array responds to `to_json` — a convenient shorthand.
Converting JSON to Ruby (Deserialization)
`JSON.parse` converts a JSON string to a Ruby Hash or Array with string keys by default. Pass `symbolize_names: true` to get symbol keys.
1. JSON.parse
`JSON.parse` returns a Hash (for JSON objects) or Array (for JSON arrays).
2. symbolize_names: true
Pass `symbolize_names: true` to get symbol keys instead of string keys.
Handling Invalid JSON
`JSON.parse` raises `JSON::ParserError` for invalid input. Always rescue this when parsing untrusted data.
1. Rescuing JSON::ParserError
Wrap `JSON.parse` in a rescue block when input comes from external sources.
Deep Cloning with JSON
A round-trip through JSON (`parse(generate(obj))`) creates a deep copy of any JSON-compatible object.
1. JSON Round-trip Deep Clone
Serialize then deserialize to get a fully independent copy.
Validating a JSON String
Ruby has no built-in `JSON.valid?` method, but you can write one using `JSON.parse` inside a rescue block.
1. Writing a json_valid? Helper
Attempt to parse — if it succeeds the JSON is valid.
2. Reading & Writing JSON Files
Load JSON from a file and write JSON back to a file.