Using JSON with Ruby

suggest change

JSON (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}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents