JSON helps us save and share data in a simple text format. Ruby's JSON library makes it easy to turn Ruby data into JSON and back.
JSON library basics in Ruby
require 'json' # Convert Ruby object to JSON string json_string = JSON.generate(ruby_object) # Convert JSON string to Ruby object ruby_object = JSON.parse(json_string)
Use require 'json' to load the JSON library before using it.
JSON.generate turns Ruby data into a JSON string.
JSON.parse turns a JSON string back into Ruby data.
require 'json' ruby_hash = {"name" => "Alice", "age" => 30} json_str = JSON.generate(ruby_hash) puts json_str
require 'json' json_str = '{"name":"Bob","age":25}' ruby_hash = JSON.parse(json_str) puts ruby_hash["name"]
require 'json' ruby_array = [1, 2, 3, "four"] json_str = JSON.generate(ruby_array) puts json_str
This program shows how to convert a Ruby hash to a JSON string and then back to a Ruby hash. It prints both the JSON string and the Ruby hash values.
require 'json' # Create a Ruby hash person = {"name" => "Emma", "city" => "Paris", "age" => 28} # Convert Ruby hash to JSON string json_data = JSON.generate(person) puts "JSON string:" puts json_data # Convert JSON string back to Ruby hash ruby_data = JSON.parse(json_data) puts "\nRuby hash from JSON:" puts ruby_data puts "Name: #{ruby_data['name']}"
JSON keys are always strings, so Ruby symbols become strings in JSON.
When parsing JSON, Ruby creates hashes with string keys, not symbols.
Use JSON.pretty_generate if you want nicely formatted JSON output.
Ruby's JSON library helps convert Ruby data to JSON strings and back.
Use JSON.generate to create JSON strings from Ruby objects.
Use JSON.parse to read JSON strings into Ruby objects.
Practice
What does the Ruby JSON.parse method do?
Solution
Step 1: Understand JSON.parse purpose
The methodJSON.parsereads a JSON formatted string and converts it into a Ruby data structure like a hash or array.Step 2: Compare with other JSON methods
JSON.generatedoes the opposite by converting Ruby objects into JSON strings.Final Answer:
Converts a JSON string into a Ruby object -> Option CQuick Check:
JSON.parse = JSON string to Ruby object [OK]
- Confusing parse with generate
- Thinking parse writes files
- Assuming parse converts Ruby to JSON
Which of the following is the correct way to convert a Ruby hash {"name" => "Alice"} to a JSON string?
Solution
Step 1: Identify method to convert Ruby object to JSON string
JSON.generateconverts Ruby objects like hashes into JSON strings.Step 2: Check other methods
JSON.parsereads JSON strings,JSON.loadis similar to parse but less common,JSON.dumpalso converts Ruby objects but requires a string or IO target.Final Answer:
JSON.generate({"name" => "Alice"}) -> Option AQuick Check:
generate = Ruby object to JSON string [OK]
- Using parse instead of generate
- Confusing dump with parse
- Passing Ruby hash directly to parse
What is the output of this Ruby code?
require 'json'
json_str = '{"age":30,"city":"NY"}'
ruby_obj = JSON.parse(json_str)
puts ruby_obj["city"]Solution
Step 1: Parse JSON string into Ruby hash
The string{"age":30,"city":"NY"}is parsed into a Ruby hash with keys "age" and "city".Step 2: Access the value for key "city"
Usingruby_obj["city"]returns the string "NY".Final Answer:
NY -> Option DQuick Check:
JSON.parse + key access = value [OK]
- Expecting numeric output instead of string
- Using symbol keys instead of string keys
- Forgetting to require 'json'
Identify the error in this Ruby code snippet:
require 'json'
json_str = '{"name": "Bob", "age": 25}'
ruby_obj = JSON.generate(json_str)
puts ruby_objSolution
Step 1: Check method usage
JSON.generateexpects a Ruby object (like a hash), but here it is given a JSON string.Step 2: Understand correct usage
To convert JSON string to Ruby object, useJSON.parse. To convert Ruby object to JSON string, useJSON.generate.Final Answer:
Using JSON.generate on a JSON string instead of a Ruby object -> Option AQuick Check:
generate needs Ruby object, not JSON string [OK]
- Confusing generate and parse
- Passing string to generate
- Ignoring error messages
You have a Ruby array [1, 2, 3]. You want to convert it to a JSON string and then back to a Ruby array. Which sequence of methods correctly does this?
Solution
Step 1: Convert Ruby array to JSON string
JSON.dump([1, 2, 3])converts the Ruby array into a JSON string.Step 2: Convert JSON string back to Ruby array
JSON.loadreads the JSON string and returns the Ruby array.Step 3: Verify other options
JSON.dump(JSON.parse([1, 2, 3])) tries to parse a Ruby array (invalid); JSON.generate(JSON.parse([1, 2, 3])) tries to parse a Ruby array (invalid); JSON.dump(JSON.load([1, 2, 3])) tries to load a Ruby array (invalid).Final Answer:
JSON.load(JSON.dump([1, 2, 3])) -> Option BQuick Check:
dump then load = Ruby array round-trip [OK]
- Parsing Ruby objects instead of JSON strings
- Using generate with parse incorrectly
- Confusing dump/load with generate/parse
Ready to prove it?
Pass the test and this pattern moves unknown
