Ruby : How to parse a jsonp and save json data to database

安稳与你 提交于 2019-12-11 09:31:12

问题


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

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

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.


回答1:


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.

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.

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)

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] 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




回答2:


If what you're really trying to do is parse the Amazon price list JS file into Ruby, there is a better (read: safer--no evals) way to do it:

require 'net/http'
require 'json'

JSON.parse(
  Net::HTTP.get(
    URI.parse('http://a0.awsstatic.com/pricing/1/ec2/rhel-od.min.js')
  ).split('callback(')[1].sub(');', '').gsub(/(\w+):/, '"\1":')
)



回答3:


As the data is as a raw JS object form, it's actually valid Ruby:

require 'json'
data = '{key: "value", key2: 33}'
obj = eval data
obj[:key]
#=> "value"
obj.to_json
# => "{\"key\":\"value\",\"key2\":33}" 

You must trust your source completely though - this would allow the running of abstract Ruby code if the data were tampered with - which could in turn run abstract command-line terminal code, using the back-tick operators. This could delete your hard drive for example.



来源:https://stackoverflow.com/questions/25641162/ruby-how-to-parse-a-jsonp-and-save-json-data-to-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!