Using JSON with Ruby
suggest changeJSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data.
In Ruby you can work with JSON directly.
First require 'json'. You can then parse a JSON string with JSON.parse:
require 'json'
j = '{"a": 1, "b": 2}'
puts JSON.parse(j)
# >> {"a" => 1, "b" => 2}
What happens here is that the parser generates a Ruby Hash from the JSON.
The other way around, generating JSON out of a Ruby hash is as simple as parsing. The method of choice is to_json:
require 'json'
hash = { 'a' => 1, 'b' => 2 }
json = hash.to_json
puts json
# >> {"a":1,"b":2}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents