Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm looking for a simple way to parse JSON, extract a value and write it into a database in Rails.

Specifically what I'm looking for, is a way to extract shortUrl from the JSON returned from the bit.ly API:

{   "errorCode": 0,   "errorMessage": "",   "results":   {     "http://www.foo.com":     {        "hash": "e5TEd",        "shortKeywordUrl": "",        "shortUrl": "http://bit.ly/1a0p8G",        "userHash": "1a0p8G"     }   },   "statusCode": "OK" } 

And then take that shortUrl and write it into an ActiveRecord object associated with the long URL.

This is one of those things that I can think through entirely in concept and when I sit down to execute I realize I've got a lot to learn.

like image 465
Dan Sinker Avatar asked Dec 01 '09 14:12

Dan Sinker


People also ask

Are duplicate keys allowed in JSON?

What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

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.

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.


1 Answers

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'.

like image 120
pguardiario Avatar answered Nov 08 '22 11:11

pguardiario