rails parser json

You have 1 new answer. See your responses.
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://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.

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

link | flag

40% accept rate
add comment

2 Answers

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
posted on 2010-11-11 08:37  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2010/11/11/1874536.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值