Ruby Language JSON with Ruby Using JSON with Ruby

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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}


Got any Ruby Language Question?