好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

rails parser json

rails parser json

You have 1 new answer. See your  responses .


Rails and JSON: a beginner's question

up vote 1 down vote favorite

2

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

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

{ "errorCode": 0, "errorMessage": "", "results": { "http://HdhCmsTestfoo测试数据": { "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.

Thoughts? Help? Any and all would be much appreciated.

link | flag

edited  Dec 3 '09 at 21:12

chollida
2,088 6 17

asked  Dec 1 '09 at 14:58

Dan Sinker
59 5


40% accept rate

add comment

start a bounty

2 Answers

oldest newest votes

up vote 4 down vote

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 . save
end

link | flag

查看更多关于rails parser json的详细内容...

  阅读:107次