DevToolsForYou

JSON Formatter, Minifier, and Validator in Ruby — Code Examples

JSON Formatter, Minifier, and Validator in RubyUse the online tool →

JSON parsing and serialisation is built into every major language. Here is how to parse a JSON string, format (pretty-print) JSON, and handle common edge cases in each language.

Ruby's standard library includes the json gem. Use JSON.parse to decode and JSON.generate (or JSON.pretty_generate) to encode.

Ruby
require 'json'

# Parse JSON string → hash
data = JSON.parse('{"name":"Alice","age":30}')
puts data["name"] # Alice

# Parse with symbol keys
data_sym = JSON.parse('{"name":"Alice","age":30}', symbolize_names: true)
puts data_sym[:name] # Alice

# Serialize hash → JSON
json_str = JSON.generate(data)
puts json_str # {"name":"Alice","age":30}

# Pretty-print
pretty = JSON.pretty_generate(data)
puts pretty

# Error handling
begin
  JSON.parse("invalid json")
rescue JSON::ParserError => e
  puts "Parse error: #{e.message}"
end

# Arrays and nested objects work the same way
puts [1, "hello", nil, true].to_json # [1,"hello",null,true]
Notes & gotchas
  • symbolize_names: true converts all string keys to symbols — convenient but use with caution on untrusted input (Symbol objects are not GC'd in older Ruby versions).
  • JSON.generate and .to_json produce the same output; .to_json is added to all objects by the json gem.
  • Rescue JSON::ParserError (not StandardError) for precise error handling on malformed input.
Try it in your browser

Need to json formatter without writing code? The JSON Formatter, Minifier, and Validator runs entirely in your browser — paste your input and get the result instantly. No signup, no install, no data sent to a server.

Open JSON Formatter
JSON Formatter, Minifier, and Validator in other languages