JSON (JavaScript Object Notation) is a lightweight data interchange format. Ruby provides built-in support for parsing JSON, making it easy to work with this popular data format.
JSON represents data as key-value pairs, similar to Ruby's Ruby Hashes. It's commonly used for data exchange between web services and APIs.
Ruby's standard library includes a JSON module for parsing and generating JSON data. To use it, you'll need to require the 'json' library:
require 'json'
To parse a JSON string into a Ruby object, use the JSON.parse
method:
json_string = '{"name": "Ruby", "age": 25}'
parsed_data = JSON.parse(json_string)
puts parsed_data["name"] # Output: Ruby
puts parsed_data["age"] # Output: 25
You can also parse JSON data from a file:
file_content = File.read('data.json')
parsed_data = JSON.parse(file_content)
# Access the parsed data
puts parsed_data["key"]
Once parsed, you can work with the JSON data as you would with regular Ruby Ruby Hashes and Ruby Arrays.
For nested JSON structures, you can chain key access:
complex_json = '{"user": {"name": "Alice", "details": {"age": 30, "city": "New York"}}}'
parsed_data = JSON.parse(complex_json)
puts parsed_data["user"]["details"]["city"] # Output: New York
To convert Ruby objects to JSON, use the to_json
method:
ruby_object = { name: "Ruby", version: 3.0 }
json_string = ruby_object.to_json
puts json_string # Output: {"name":"Ruby","version":3.0}
JSON.parse(json_string, symbolize_names: true)
to convert keys to symbols for performance in large datasets.Ruby's JSON parsing capabilities make it straightforward to work with JSON data. Whether you're consuming APIs or building web services, understanding JSON parsing is crucial for modern Ruby development.
For more advanced data handling, explore Ruby Hashes and Ruby Arrays, which are fundamental to working with parsed JSON data efficiently.