Codectionary / Developer documentation / Ruby

JSON Parsing and Generation

JSON converts portable data between text and Ruby hashes, arrays and scalar values. Parsed object keys are strings by default. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

JSON.parse(text); JSON.generate(value)

Examples

JSON Parsing and Generation

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

require "json"
profile = JSON.parse('{"name":"Ada","visits":2}')
profile["visits"] += 1
puts profile["name"]
puts JSON.generate(profile)
  1. Expected output: Ada {"name":"Ada","visits":3}
  2. The numeric JSON value becomes an Integer and can be incremented directly. Generation preserves the hash insertion order in this example.

Best practices

  • Validate required fields and types after parsing.
  • Keep untrusted JSON as ordinary data; avoid object-restoration extensions.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading