Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a JSON string in Ruby

Tags:

json

ruby

I have a string that I want to parse in Ruby:

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}' 

Is there an easy way to extract the data?

like image 340
Rod Avatar asked Mar 23 '11 19:03

Rod


People also ask

What does JSON parse do in Ruby?

JSON. parse, called with option create_additions , uses that information to create a proper Ruby object.

Is JSON parse safe Ruby?

There are no security concerns possible. JSON isn't code, you can't inject harmful values into it. JSON. parse is safe.

What does JSON parse do in Rails?

One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.


2 Answers

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:

  • YAJL C Bindings for Ruby
  • JSON::Stream
like image 57
Greg Avatar answered Sep 30 '22 21:09

Greg


Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example require "rubygems" # don't need this if you're Ruby v1.9.3 or higher require "json"  string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}' parsed = JSON.parse(string) # returns a hash  p parsed["desc"]["someKey"] p parsed["main_item"]["stats"]["a"]  # Read JSON from a file, iterate over objects file = open("shops.json") json = file.read  parsed = JSON.parse(json)  parsed["shop"].each do |shop|   p shop["id"] end 
like image 32
nevan king Avatar answered Sep 30 '22 20:09

nevan king