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

2019-01-01 09:38发布

This question already has an answer here:

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.

13条回答
临风纵饮
2楼-- · 2019-01-01 10:25

Here's what I would do:

json = "{\"errorCode\":0,\"errorMessage\":\"\",\"results\":{\"http://www.foo.com\":{\"hash\":\"e5TEd\",\"shortKeywordUrl\":\"\",\"shortUrl\":\"http://b.i.t.ly/1a0p8G\",\"userHash\":\"1a0p8G\"}},\"statusCode\":\"OK\"}"

hash = JSON.parse(json)
results = hash[:results]

If you know the source url then you can use:

source_url = "http://www.foo.com".to_sym

results.fetch(source_url)[:shortUrl]
=> "http://b.i.t.ly/1a0p8G"

If you don't know the key for the source url you can do the following:

results.fetch(results.keys[0])[:shortUrl]
=> "http://b.i.t.ly/1a0p8G"

If you're not wanting to lookup keys using symbols, you can convert the keys in the hash to strings:

results = json[:results].stringify_keys

results.fetch(results.keys[0])["shortUrl"]
=> "http://b.i.t.ly/1a0p8G"

If you're concerned the JSON structure might change you could build a simple JSON Schema and validate the JSON before attempting to access keys. This would provide a guard.

NOTE: Had to mangle the bit.ly url because of posting rules.

查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 10:26

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

查看更多
流年柔荑漫光年
4楼-- · 2019-01-01 10:26

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
查看更多
几人难应
5楼-- · 2019-01-01 10:31
require 'json'

hash = JSON.parse string

work with the hash and do what you want to do.

查看更多
深知你不懂我心
6楼-- · 2019-01-01 10:36

RUBY is case sensitive.

require 'json' # json must be lower case

JSON.parse(<json object>)  

for example

JSON.parse(response.body) # JSON must be all upper-case
查看更多
宁负流年不负卿
7楼-- · 2019-01-01 10:37

Ruby has a JSON parser:

require 'json'
查看更多
登录 后发表回答