Bird
Raised Fist0
Rubyprogramming~10 mins

JSON library basics in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - JSON library basics
Start
↓
Require 'json'
↓
Create Ruby object
↓
Convert to JSON string
↓
Parse JSON string back
↓
Use Ruby object
↓
End
This flow shows how to load the JSON library, convert Ruby objects to JSON strings, and parse JSON strings back to Ruby objects.
Execution Sample
Ruby
require 'json'

person = {"name" => "Alice", "age" => 30}

json_str = JSON.generate(person)

ruby_obj = JSON.parse(json_str)

puts ruby_obj["name"]
This code converts a Ruby hash to a JSON string and then parses it back to a Ruby hash, printing the name.
Execution Table
StepActionCode/ExpressionResult/ValueNotes
1Require JSON libraryrequire 'json'JSON module loadedMakes JSON methods available
2Create Ruby hashperson = {"name" => "Alice", "age" => 30}{"name"=>"Alice", "age"=>30}Ruby hash with keys and values
3Convert Ruby hash to JSON stringjson_str = JSON.generate(person){"name":"Alice","age":30}JSON string format
4Parse JSON string back to Ruby hashruby_obj = JSON.parse(json_str){"name"=>"Alice", "age"=>30}Ruby hash recreated
5Access value from Ruby hashputs ruby_obj["name"]AlicePrints the name value
6End--Program ends
💡 All steps completed successfully, program ends after printing 'Alice'
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
personnil{"name"=>"Alice", "age"=>30}{"name"=>"Alice", "age"=>30}{"name"=>"Alice", "age"=>30}{"name"=>"Alice", "age"=>30}
json_strnilnil{"name":"Alice","age":30}{"name":"Alice","age":30}{"name":"Alice","age":30}
ruby_objnilnilnil{"name"=>"Alice", "age"=>30}{"name"=>"Alice", "age"=>30}
Key Moments - 3 Insights
Why do we need to require 'json' before using JSON methods?
The require 'json' line loads the JSON library so Ruby knows how to convert objects to and from JSON. Without it, JSON.generate and JSON.parse won't work (see Step 1 in execution_table).
Why does the Ruby hash look different from the JSON string?
Ruby hashes use => for key-value pairs and keys can be symbols or strings. JSON strings use colon : and keys are always strings. This difference is shown in Step 2 vs Step 3 in execution_table.
What type is ruby_obj after parsing JSON?
After JSON.parse, ruby_obj is a Ruby hash, not a string. It has the same structure as the original hash (Step 4 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of json_str after Step 3?
A{"name":"Alice","age":30}
B{"name"=>"Alice", "age"=>30}
Cnil
DJSON module loaded
💡 Hint
Check the 'Result/Value' column for Step 3 in execution_table.
At which step does ruby_obj get assigned a Ruby hash?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Action' and 'Result/Value' columns in execution_table for when ruby_obj is assigned.
If we skip requiring 'json', what happens when calling JSON.generate?
AIt works normally
BIt raises an error because JSON is not loaded
CIt returns nil
DIt prints the Ruby hash directly
💡 Hint
Refer to Step 1 in execution_table and key_moments about requiring the library.
Concept Snapshot
require 'json' to load JSON methods
Use JSON.generate(obj) to convert Ruby object to JSON string
Use JSON.parse(str) to convert JSON string back to Ruby object
JSON keys are always strings; Ruby hash keys can be symbols or strings
Parsed JSON returns Ruby hashes and arrays
Always require 'json' before using JSON methods
Full Transcript
This example shows how to use Ruby's JSON library. First, require 'json' loads the library so you can use JSON methods. Then, a Ruby hash named person is created with keys 'name' and 'age'. Using JSON.generate, this hash is converted into a JSON string format. Next, JSON.parse converts the JSON string back into a Ruby hash named ruby_obj. Finally, accessing ruby_obj['name'] prints 'Alice'. The execution table traces each step, showing variable values and actions. Key moments clarify why requiring the library is necessary, the difference between Ruby hashes and JSON strings, and the type of object returned by parsing JSON. The quiz tests understanding of these steps. This process is essential for working with JSON data in Ruby.

Practice

(1/5)
1.

What does the Ruby JSON.parse method do?

easy
A. Reads a file from disk
B. Converts a Ruby object into a JSON string
C. Converts a JSON string into a Ruby object
D. Writes a JSON string to a file

Solution

  1. Step 1: Understand JSON.parse purpose

    The method JSON.parse reads a JSON formatted string and converts it into a Ruby data structure like a hash or array.
  2. Step 2: Compare with other JSON methods

    JSON.generate does the opposite by converting Ruby objects into JSON strings.
  3. Final Answer:

    Converts a JSON string into a Ruby object -> Option C
  4. Quick Check:

    JSON.parse = JSON string to Ruby object [OK]
Hint: Remember: parse means read JSON into Ruby [OK]
Common Mistakes:
  • Confusing parse with generate
  • Thinking parse writes files
  • Assuming parse converts Ruby to JSON
2.

Which of the following is the correct way to convert a Ruby hash {"name" => "Alice"} to a JSON string?

easy
A. JSON.generate({"name" => "Alice"})
B. JSON.dump({"name" => "Alice"}, $stdout)
C. JSON.load({"name" => "Alice"})
D. JSON.parse({"name" => "Alice"})

Solution

  1. Step 1: Identify method to convert Ruby object to JSON string

    JSON.generate converts Ruby objects like hashes into JSON strings.
  2. Step 2: Check other methods

    JSON.parse reads JSON strings, JSON.load is similar to parse but less common, JSON.dump also converts Ruby objects but requires a string or IO target.
  3. Final Answer:

    JSON.generate({"name" => "Alice"}) -> Option A
  4. Quick Check:

    generate = Ruby object to JSON string [OK]
Hint: Use generate to make JSON strings from Ruby hashes [OK]
Common Mistakes:
  • Using parse instead of generate
  • Confusing dump with parse
  • Passing Ruby hash directly to parse
3.

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"]
medium
A. SyntaxError
B. 30
C. nil
D. NY

Solution

  1. 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".
  2. Step 2: Access the value for key "city"

    Using ruby_obj["city"] returns the string "NY".
  3. Final Answer:

    NY -> Option D
  4. Quick Check:

    JSON.parse + key access = value [OK]
Hint: Parse JSON then access keys like a hash [OK]
Common Mistakes:
  • Expecting numeric output instead of string
  • Using symbol keys instead of string keys
  • Forgetting to require 'json'
4.

Identify the error in this Ruby code snippet:

require 'json'
json_str = '{"name": "Bob", "age": 25}'
ruby_obj = JSON.generate(json_str)
puts ruby_obj
medium
A. Using JSON.generate on a JSON string instead of a Ruby object
B. Missing require 'json' statement
C. Incorrect JSON string format
D. Using puts instead of print

Solution

  1. Step 1: Check method usage

    JSON.generate expects a Ruby object (like a hash), but here it is given a JSON string.
  2. Step 2: Understand correct usage

    To convert JSON string to Ruby object, use JSON.parse. To convert Ruby object to JSON string, use JSON.generate.
  3. Final Answer:

    Using JSON.generate on a JSON string instead of a Ruby object -> Option A
  4. Quick Check:

    generate needs Ruby object, not JSON string [OK]
Hint: Use parse for strings, generate for Ruby objects [OK]
Common Mistakes:
  • Confusing generate and parse
  • Passing string to generate
  • Ignoring error messages
5.

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?

hard
A. JSON.dump(JSON.parse([1, 2, 3]))
B. JSON.load(JSON.dump([1, 2, 3]))
C. JSON.generate(JSON.parse([1, 2, 3]))
D. JSON.dump(JSON.load([1, 2, 3]))

Solution

  1. Step 1: Convert Ruby array to JSON string

    JSON.dump([1, 2, 3]) converts the Ruby array into a JSON string.
  2. Step 2: Convert JSON string back to Ruby array

    JSON.load reads the JSON string and returns the Ruby array.
  3. 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).
  4. Final Answer:

    JSON.load(JSON.dump([1, 2, 3])) -> Option B
  5. Quick Check:

    dump then load = Ruby array round-trip [OK]
Hint: Use dump then load for Ruby object to JSON and back [OK]
Common Mistakes:
  • Parsing Ruby objects instead of JSON strings
  • Using generate with parse incorrectly
  • Confusing dump/load with generate/parse
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard