How do I parse JSON with Ruby on Rails? [duplicate] How do I parse JSON with Ruby on Rails? [duplicate] ruby ruby

How do I parse JSON with Ruby on Rails? [duplicate]


These answers are a bit dated. Therefore I give you:

hash = JSON.parse string

Rails should automagically load the json module for you, so you don't need to add require 'json'.


Parsing JSON in Rails is quite straightforward:

parsed_json = ActiveSupport::JSON.decode(your_json_string)

Let's suppose, the object you want to associate the shortUrl with is a Site object, which has two attributes - short_url and long_url. Than, to get the shortUrl and associate it with the appropriate Site object, you can do something like:

parsed_json["results"].each do |longUrl, convertedUrl|  site = Site.find_by_long_url(longUrl)  site.short_url = convertedUrl["shortUrl"]  site.saveend


This answer is quite old. pguardiario's got it.

One site to check out is JSON implementation for Ruby. This site offers a gem you can install for a much faster C extension variant.

With the benchmarks given their documentation page they claim that it is 21.500x faster than ActiveSupport::JSON.decode

The code would be the same as Milan Novota's answer with this gem, but the parsing would just be:

parsed_json = JSON(your_json_string)