Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 134 ยท Standard Library

JSON

Learn JSON in Ruby - JSON.parse and symbolize_names, JSON.generate and pretty_generate, writing custom to_json for your classes, handling ParserError, type mapping and common pitfalls.

JSON (JavaScript Object Notation) is the common language of web APIs, configuration files and log lines. It has only a handful of types: objects, arrays, strings, numbers, true, false and null. Ruby's json library, which ships with Ruby, converts between JSON text and ordinary Ruby hashes, arrays, strings, numbers, booleans and nil. You load it with require 'json', and then you have JSON.parse to read, JSON.generate and to_json to write, and JSON.pretty_generate for human-readable output.

The mapping is so natural that you often forget a conversion happens. That is also where the bugs hide: symbols turn into strings, your own objects become strings unless you teach them how to serialize, and invalid input raises an exception you must handle. This lesson covers all of it, building on hashes, arrays and exceptions.

Parsing JSON text

Ruby JSON.parse and the type mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

JSON objects become Hash with string keys, arrays become Array, null becomes nil, whole numbers become Integer and numbers with a fraction or exponent become Float. A JSON document may be any value, not only an object or array: JSON.parse("42") is 42.

symbolize_names

Ruby code usually prefers symbol keys. Ask for them when you parse:

Ruby symbolize_names: true

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Mixing key types is the most common JSON bug: data[:user] returns nil for a hash with string keys, with no error. Pick one convention at the boundary, usually symbolize_names: true, and stay with it. The pattern-matching example uses what you learned in Pattern Matching, which needs symbol keys.

Generating JSON

Ruby to_json, JSON.generate and pretty_generate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

to_json is added to Hash, Array, String, Integer, Float, true, false and nil once you require json. The result is compact text with no spaces. JSON.pretty_generate indents with two spaces, ideal for config files and for looking at data while debugging. In a round trip the data compares equal here because the keys were symbols and were symbolized again; with string keys on the way in, symbolize_names would produce a different hash.

JSON has no symbol type, so symbols are written as strings and come back as strings. It also has no way to say "this was an Integer key": object keys are always strings.

Your own objects and custom to_json

By default a plain object does not become a JSON object. Look what happens:

Ruby Default serialization of your own class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Without help, the object is turned into the string returned by to_s, which for a plain object looks like "#<Point:0x000...>" and contains a memory address (the example prints only checks on it for that reason). A Struct and a Data do the same: Pair.new(1, 2).to_json prints "#<struct Pair left=1, right=2>" and the Data prints "#<data a=1>", a JSON string, not an object. That is almost never what you want, so give your classes a to_h and a to_json.

Ruby A custom to_json that works with nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice to_json(*args): the library passes a state object to nested to_json calls (it carries settings such as indentation), and forwarding it keeps generate and pretty_generate working for objects inside arrays and hashes. If you write def to_json with no parameters, putting the object in an array and generating JSON raises ArgumentError: wrong number of arguments (given 1, expected 0). The same shape works for Struct and Data: call to_h and convert that.

A small, reliable convention is: every serializable class has to_h (what to write), and the JSON code calls to_h.to_json. Reading is the reverse with a from_h class method. This keeps the format in one place and makes it easy to test.

Handling bad input

JSON from files, users or the network can be broken. JSON.parse raises JSON::ParserError, a subclass of StandardError.

Ruby JSON::ParserError (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The run ends with JSON::ParserError and a message that points at the problem: expected object key, got: '}' at line 1 column 16. (The exact wording depends on the version of the json library, and the backtrace starts inside the library, so read the from main.rb:3 line to find your own code.) Trailing commas, single quotes, unquoted keys and comments are all invalid JSON. Rescue it where the text enters your program:

Ruby Rescuing parse errors and validating shape

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two layers of checking are normal: the parser guarantees the text is valid JSON, and your code checks that the content has the shape it expects (fetch for required keys, Integer() for strict number conversion). JSON.generate refuses NaN and Infinity because JSON cannot represent them, raising JSON::GeneratorError.

Useful options and variants

  • JSON.parse(text, symbolize_names: true): symbol keys.
  • JSON.pretty_generate(obj): indented output; JSON.generate(obj) and obj.to_json: compact.
  • JSON.parse(text, object_class: OpenStruct) and array_class: build other containers (see Set, OpenStruct and Friends); rarely needed.
  • JSON.dump(obj) and JSON.load(text): older, more permissive API. Prefer generate and parse; JSON.load can revive objects in some configurations and is a security smell for untrusted input.
  • JSON.parse(text, max_nesting: 20): limit depth. The default is 100 and protects you from absurdly nested documents.
  • Files: JSON.parse(File.read(path)) and File.write(path, JSON.pretty_generate(data)) (see Files and IO).
  • Line-oriented logs ("JSON Lines"): one to_json per line, then text.each_line.map { |line| JSON.parse(line) }.
Ruby JSON Lines and a small transform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pitfalls checklist

  • Key types. Strings after parse unless you pass symbolize_names: true.
  • Symbols and numbers as keys are turned into strings when written.
  • Your objects need to_json(*args) or a conversion to a hash before serializing.
  • Time objects are written as strings via to_s; use time.iso8601 (after require 'time') so other systems can read them.
  • Floats like 0.1 + 0.2 are written with their full digits (0.30000000000000004); round before serializing if you want tidy numbers. Money belongs in integers (cents) or strings.
  • Untrusted input. JSON.parse is safe for untrusted text; avoid JSON.load and create_additions: true, which can instantiate arbitrary classes.
  • Encoding. JSON text should be UTF-8. Read files with the right encoding and let JSON.generate escape the rest.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After data = JSON.parse('{"a": 1}'), what does data[:a] return?

    By default parsed objects have string keys, so the symbol :a finds nothing. Use data["a"] or pass symbolize_names: true.
  2. 2. What happens when you call to_json on an ordinary object that has no to_json of its own?

    The generic Object#to_json writes to_s as a string. Define to_json (usually via to_h) to get a JSON object.
  3. 3. Why should a custom method be written def to_json(*args) and forward the arguments?

    The generator hands a state object to nested to_json calls. A method with no parameters raises ArgumentError in those cases.
  4. 4. Which exception is raised for the invalid text {"a": }?

    JSON.parse raises JSON::ParserError, a StandardError, for text that is not valid JSON.
  5. 5. Which pair is the recommended way to read and write JSON for untrusted data?

    parse and generate are strict and safe. load is more permissive and has historically been a source of security problems; eval and Marshal must never touch untrusted text.

Summary

  • require 'json', then JSON.parse(text) reads and to_json, JSON.generate and JSON.pretty_generate write.
  • Objects become hashes with string keys, so use symbolize_names: true for symbol keys; arrays, strings, numbers, booleans and nil map directly.
  • Your own classes need to_h and to_json(*args); otherwise they are written as strings.
  • Rescue JSON::ParserError at the boundary, then validate the shape with fetch, is_a? and Integer().
  • Prefer parse and generate over load and dump; store money as integers and times as ISO 8601 strings.

Next: YAML and CSV