How to Read JSON in Ruby: Simple Guide with Examples
To read JSON in Ruby, use the
JSON.parse method from the built-in json library. First, require the library with require 'json', then call JSON.parse(json_string) to convert a JSON string into a Ruby hash or array.Syntax
To read JSON in Ruby, you need to:
- Require the JSON library:
require 'json' - Parse the JSON string: Use
JSON.parse(json_string)to convert JSON text into Ruby data structures like hashes or arrays.
ruby
require 'json'
ruby_object = JSON.parse(json_string)Example
This example shows how to read a JSON string and access its data as a Ruby hash.
ruby
require 'json' json_string = '{"name": "Alice", "age": 30, "languages": ["Ruby", "Python"]}' ruby_hash = JSON.parse(json_string) puts "Name: #{ruby_hash['name']}" puts "Age: #{ruby_hash['age']}" puts "Languages: #{ruby_hash['languages'].join(', ')}"
Output
Name: Alice
Age: 30
Languages: Ruby, Python
Common Pitfalls
Common mistakes when reading JSON in Ruby include:
- Forgetting to
require 'json', which causesNameError. - Trying to parse invalid JSON strings, which raises
JSON::ParserError. - Accessing keys with symbols instead of strings, since
JSON.parsereturns keys as strings by default.
To avoid symbol key issues, you can use JSON.parse(json_string, symbolize_names: true) to get symbol keys.
ruby
require 'json' json_string = '{"key": "value"}' # Wrong: keys are strings, not symbols ruby_hash = JSON.parse(json_string) puts ruby_hash[:key] # => nil # Right: use symbolize_names option ruby_hash_sym = JSON.parse(json_string, symbolize_names: true) puts ruby_hash_sym[:key] # => "value"
Output
nil
value
Quick Reference
| Action | Code Example |
|---|---|
| Require JSON library | require 'json' |
| Parse JSON string | JSON.parse(json_string) |
| Parse with symbol keys | JSON.parse(json_string, symbolize_names: true) |
| Handle parse errors | begin JSON.parse(bad_json) rescue JSON::ParserError => e puts "Invalid JSON: #{e.message}" end |
Key Takeaways
Always require the 'json' library before parsing JSON in Ruby.
Use JSON.parse to convert JSON strings into Ruby hashes or arrays.
By default, keys are strings; use symbolize_names: true to get symbol keys.
Handle JSON::ParserError to catch invalid JSON data gracefully.
Access parsed data using string or symbol keys depending on parsing options.