Consider this Ruby code that uses the JSON library to parse a JSON string. What will be printed?
require 'json' json_str = '{"name":"Alice","age":30}' obj = JSON.parse(json_str) puts obj["name"]
Think about what JSON.parse returns and how to access values in the resulting object.
JSON.parse converts the JSON string into a Ruby hash. Accessing obj["name"] returns the string "Alice".
This Ruby code creates a hash and converts it to a JSON string. What is the output?
require 'json' hash = {"city" => "Paris", "country" => "France"} puts JSON.generate(hash)
Remember JSON keys and string values must be in double quotes.
JSON.generate converts the Ruby hash into a JSON string with keys and string values quoted properly.
Look at this Ruby code snippet. What error will it raise when run?
require 'json' json_str = '{name: "Bob", age: 25}' obj = JSON.parse(json_str)
Check if the JSON string is valid JSON format.
The JSON string uses unquoted keys, which is invalid JSON. JSON.parse raises JSON::ParserError.
Which method from the JSON library converts a Ruby object like a hash or array into a JSON formatted string?
Think about the method that creates JSON text from Ruby objects.
JSON.generate takes a Ruby object and returns a JSON string representation.
Given this Ruby code, how many keys does the resulting hash have?
require 'json' json_str = '{"a":1,"b":2,"c":{"d":4}}' obj = JSON.parse(json_str) puts obj.keys.size
Count only the top-level keys in the parsed hash.
The JSON string has three top-level keys: "a", "b", and "c". The nested keys inside "c" do not count at the top level.