Generate and Parse JSON in Ruby
1 minsJSON is a language-agnostic lightweight data-interchange format. It’s easy to read and understand both by humans and machines. Ruby has a built-in module that contains methods to generate and parse JSON.
In this article, you’ll learn how to generate and parse JSON data in Ruby.
JSON.generate(): Generating or Serializing JSON in Ruby
You can serialize a Ruby type to JSON using the JSON.generate()
function like so -
require 'json'
my_hash = {:name => "John", :age => 25, :phones => ["+1-9920394631", "+1-8928374743"], :address => {:city => "New York", :country => "USA"}}
json_data = JSON.generate(my_hash)
puts json_data
# Output
{"name":"John","age":25,"phones":["+1-9920394631","+1-8928374743"],"address":{"city":"New York","country":"USA"}}
JSON.parse(): Parsing JSON string in Ruby
You can use the JSON.parse()
function to parse a json string to a Ruby hash -
require 'json'
json_data = '{"name": "Sachin", "age": 30, "phones": ["+1-9920394631", "+1-8928374743"], "address": {"city": "New York", "Country": "USA"}}'
my_hash = JSON.parse(json_data);
puts my_hash
# Output
{"name"=>"Sachin", "age"=>20, "phones"=>["+1-9920394631", "+1-8928374743"], "address"=>{"city"=>"New York", "Country"=>"USA"}}