Parsing a JSON string in Ruby
This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string
, like so:
require 'json'JSON.parse(json_string)
If you’re using an older Ruby, you may need to install the json gem.
There are also other implementations of JSON for Ruby that may fit some use-cases better:
Just to extend the answers a bit with what to do with the parsed object:
# JSON Parsing examplerequire "rubygems" # don't need this if you're Ruby v1.9.3 or higherrequire "json"string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'parsed = JSON.parse(string) # returns a hashp parsed["desc"]["someKey"]p parsed["main_item"]["stats"]["a"]# Read JSON from a file, iterate over objectsfile = open("shops.json")json = file.readparsed = JSON.parse(json)parsed["shop"].each do |shop| p shop["id"]end