Ruby:如何解析jsonp并将json数据保存到数据库 [英] Ruby : How to parse a jsonp and save json data to database

查看:226
本文介绍了Ruby:如何解析jsonp并将json数据保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析JSONP数据并将其保存到数据库中.

I want to parse the JSONP data and save that data into my data base .

我有我的jsonp网址,可以这样说>>

I have my jsonp url lets say this >>http://a0.awsstatic.com/pricing/1/ec2/pricing-data-transfer-with-regions.min.js?callback=callback&_=1409722308446

它不是普通的json对象,因此我该如何在Rails的ruby/ruby​​中解析此json并将数据保存到我的数据库中.我想将数据保存在已提交的表中,例如地区,名称,类型,价格.

Its not normal json object so how can i parse this json in ruby/ruby on rails and save the data into my database. I want to save the data in table having filed lets say region , name ,type, price .

执行相同操作的方式是什么.

What are the ways to do the same.

推荐答案

JSONP可以解决客户端JavaScript中的相同来源策略.在Ruby中处理数据不是必需的.首先,我将尝试在没有回调的情况下找到纯JSON中可用的数据.

JSONP is a work around for the same origin policy in client side JavaScript. It isn't required for processing data in Ruby. Firstly I would try to find the data available in plain JSON, without the callback.

但是,如果该URL绝对是您可以调用此数据的唯一URL,那么我将使用正则表达式删除回调,然后解析纯JSON数据.

If, however, that URL is absolutely the only one you can call for this data, then I would strip away the callback using a regular expression and then parse the plain JSON data.

如果您已经将该文件的内容加载到名为jsonp的变量中,则可能会执行以下操作:

If you have already loaded the contents of that file into a variable called jsonp, then something like this might work:

require 'net/http'
require 'json'
uri = URI.parse('http://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js?callback=callback&_=1409731896563')
jsonp = Net::HTTP.get(uri)
jsonp.gsub!(/^.*callback\(/, '') # removes the comment and callback function from the start of the string
jsonp.gsub!(/\);$/, '') # removes the end of the callback function
jsonp.gsub!(/(\w+):/, '"\1":')
hash = JSON.parse(jsonp)

然后hash将具有从响应中解析出的JSON.

then hash will have the parsed JSON from the response.

请注意,此代码没有错误处理,应将其视为最终解决方案的起点.

Please note, this code has no error handling and should be treated as a starting point for your final solution.

[edit]添加了第三个gsub,以将JavaScript样式键更改为JSON样式键.在这种情况下,这是可行的,因为所有键看上去都足够简单以适合该正则表达式. [edit2]添加了使用Net :: HTTP加载JSONP的方法

[edit] Added the third gsub to change the JavaScript style keys to JSON style keys. This works in this case because the keys all appear to be simple enough to fit that regex. [edit2] Added way to load the JSONP with Net::HTTP

这篇关于Ruby:如何解析jsonp并将json数据保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆