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.
0
0
JSON library basics in Ruby
Introduction
When you want to save data from your Ruby program to a file in a format other programs can read.
When you need to send data from your Ruby app to a web service or API that uses JSON.
When you receive JSON data from the internet and want to use it inside your Ruby program.
When you want to convert Ruby hashes or arrays into a string to store or send.
When you want to read JSON strings and turn them into Ruby objects to work with.
Syntax
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.
Examples
This converts a Ruby hash into a JSON string and prints it.
Ruby
require 'json' ruby_hash = {"name" => "Alice", "age" => 30} json_str = JSON.generate(ruby_hash) puts json_str
This converts a JSON string into a Ruby hash and prints the value for "name".
Ruby
require 'json' json_str = '{"name":"Bob","age":25}' ruby_hash = JSON.parse(json_str) puts ruby_hash["name"]
This converts a Ruby array into a JSON string and prints it.
Ruby
require 'json' ruby_array = [1, 2, 3, "four"] json_str = JSON.generate(ruby_array) puts json_str
Sample Program
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.
Ruby
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']}"
OutputSuccess
Important Notes
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.
Summary
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.