Ruby Language Using JSON with Ruby


Example

JSON (JavaScript Object Notation) is a lightweight data interchange format. Many web applications use it to send and receive data.

In Ruby you can simply work with JSON.

At first you have to require 'json', then you can parse a JSON string via the JSON.parse() command.

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 out of 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}