Ruby tutorials - json

JSON

Generate json data

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'json'
doc1 = JSON 'test1' => 12
doc2 = JSON['test2' => 12]
puts doc1
puts doc2
doc3 = JSON.generate [22, 23, {"a"=>55}, false, true, nil, 1..12]
puts doc3
doc4 = JSON.pretty_generate [22, 23, {"a"=>55}, false, true, nil, 1..12]
puts doc4

Parse json

1
2
3
4
5
6
7
8
9
require 'json'
json = JSON.parse '{"foo":"bar", "ding":"dong"}'
puts json["ding"]
str = '{"desc":{"key1":"value1","key2":"value2"},"content":{"stats":{"a":8,"b":12,"c":10}}}'
json2 = JSON.parse(str)
puts json2["desc"]["key1"]
puts json2["content"]["stats"]["b"]
Share