0
0
Rubyprogramming~20 mins

JSON library basics in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
JSON Mastery in Ruby
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code using JSON?

Consider this Ruby code that uses the JSON library to parse a JSON string. What will be printed?

Ruby
require 'json'
json_str = '{"name":"Alice","age":30}'
obj = JSON.parse(json_str)
puts obj["name"]
ASyntaxError
B30
Cnil
DAlice
Attempts:
2 left
💡 Hint

Think about what JSON.parse returns and how to access values in the resulting object.

Predict Output
intermediate
2:00remaining
What does this Ruby code output when generating JSON?

This Ruby code creates a hash and converts it to a JSON string. What is the output?

Ruby
require 'json'
hash = {"city" => "Paris", "country" => "France"}
puts JSON.generate(hash)
A{"city":"Paris","country":"France"}
B{city: "Paris", country: "France"}
C{"city":Paris,"country":France}
DSyntaxError
Attempts:
2 left
💡 Hint

Remember JSON keys and string values must be in double quotes.

🔧 Debug
advanced
2:00remaining
What error does this Ruby code raise when parsing JSON?

Look at this Ruby code snippet. What error will it raise when run?

Ruby
require 'json'
json_str = '{name: "Bob", age: 25}'
obj = JSON.parse(json_str)
ANoMethodError
BJSON::ParserError
CTypeError
DSyntaxError
Attempts:
2 left
💡 Hint

Check if the JSON string is valid JSON format.

🧠 Conceptual
advanced
2:00remaining
Which Ruby method converts a Ruby object to a JSON string?

Which method from the JSON library converts a Ruby object like a hash or array into a JSON formatted string?

AJSON.generate
BJSON.load
CJSON.parse
DJSON.read
Attempts:
2 left
💡 Hint

Think about the method that creates JSON text from Ruby objects.

🚀 Application
expert
2:00remaining
How many keys are in the Ruby hash after parsing this JSON string?

Given this Ruby code, how many keys does the resulting hash have?

Ruby
require 'json'
json_str = '{"a":1,"b":2,"c":{"d":4}}'
obj = JSON.parse(json_str)
puts obj.keys.size
A1
B4
C3
D2
Attempts:
2 left
💡 Hint

Count only the top-level keys in the parsed hash.