如何用Ruby on Rails解析JSON ?

时间:2021-06-11 20:44:13

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

我正在寻找一种解析JSON的简单方法,提取一个值并将其写入Rails中的数据库中。

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

具体来说,我想要的是,从JSON返回的JSON中提取shortUrl的方法。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.

然后将这个shortUrl写入一个ActiveRecord对象与长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 个解决方案

#1


410  

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

Rails应该自动为您加载json模块,因此不需要添加“json”。

#2


179  

Parsing JSON in Rails is quite straightforward:

在Rails中解析JSON非常简单:

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:

让我们假设,您想要将shortUrl与一个站点对象关联的对象,它有两个属性——short_url和long_url。要得到shortUrl并将其与适当的站点对象关联起来,您可以这样做:

parsed_json["results"].each do |longUrl, convertedUrl|
  site = Site.find_by_long_url(longUrl)
  site.short_url = convertedUrl["shortUrl"]
  site.save
end

#3


53  

This answer is quite old. pguardiario's got it.

这个答案相当古老。pguardiario有它。

One site to check out is JSON implementation for Ruby. This site offers a gem you can install for a much faster C extension variant.

要检查的一个站点是Ruby的JSON实现。这个站点提供了一个gem,您可以安装一个更快的C扩展变种。

With the benchmarks given their documentation page they claim that it is 21.500x faster than ActiveSupport::JSON.decode

根据他们的文档页面,他们声称它比ActiveSupport::JSON.decode快了21.500x。

The code would be the same as Milan Novota's answer with this gem, but the parsing would just be:

这段代码与米兰·诺沃塔(Milan Novota)用这颗宝石的答案是一样的,但解析只是:

parsed_json = JSON(your_json_string)

#4


18  

Here is an update for 2013.

以下是2013年的最新情况。

Ruby

Ruby 1.9 has a default JSON gem with C extensions. You can use it with

Ruby 1.9有一个带有C扩展的默认JSON gem。你可以用它。

require 'json'
JSON.parse ''{ "x": "y" }'
# => {"x"=>"y"}

The parse! variant can be used for safe sources. There are also other gems, which may be faster than the default implementation. Please refer to multi_json for the list.

解析!变体可用于安全的来源。还有其他的gem,它可能比默认的实现快。请参考列表的multi_json。

Rails

Modern versions of Rails use multi_json, a gem that automatically uses the fastest JSON gem available. Thus, the recommended way is to use

Rails的现代版本使用multi_json,这是一种自动使用最快的JSON gem的gem。因此,推荐的方法是使用。

object = ActiveSupport::JSON.decode json_string

Please refer to ActiveSupport::JSON for more information. In particular, the important line in the method source is

请参考ActiveSupport::JSON以获取更多信息。特别地,方法源中的重要行是。

data = MultiJson.load(json, options)

Then in your Gemfile, include the gems you want to use. For example,

然后在你的Gemfile中,包括你想要使用的宝石。例如,

group :production do
  gem 'oj'
end

#5


7  

Ruby's bundled JSON is capable of exhibiting a bit of magic on its own.

Ruby的绑定JSON可以自己显示一点魔法。

If you have a string containing JSON serialized data that you want to parse:

如果您有一个包含JSON序列化数据的字符串,您需要解析:

JSON[string_to_parse]

JSON will look at the parameter, see it's a String and try decoding it.

JSON会查看参数,看它是一个字符串并尝试解码它。

Similarly, if you have a hash or array you want serialized, use:

类似地,如果您想要序列化的散列或数组,请使用:

JSON[array_of_values]

Or:

或者:

JSON[hash_of_values]

And JSON will serialize it. You can also use the to_json method if you want to avoid the visual similarity of the [] method.

JSON会序列化它。如果希望避免[]方法的视觉相似性,也可以使用to_json方法。

Here are some examples:

下面是一些例子:

hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]

JSON[hash_of_values] 
# => "{\"foo\":1,\"bar\":2}"

JSON[array_of_values] 
# => "[{\"foo\":1,\"bar\":2}]"

string_to_parse = array_of_values.to_json
JSON[string_to_parse]
# => [{"foo"=>1, "bar"=>2}]

If you root around in JSON you might notice it's a subset of YAML, and, actually the YAML parser is what's handling JSON. You can do this too:

如果你在JSON中找到根,你可能会注意到它是YAML的一个子集,实际上YAML解析器是处理JSON的。你也可以这样做:

require 'yaml'

YAML.load(string_to_parse)
# => [{"foo"=>1, "bar"=>2}]

If your app is parsing both YAML and JSON, you can let YAML handle both flavors of serialized data.

如果您的应用程序正在解析YAML和JSON,您可以让YAML处理两种类型的序列化数据。

#6


5  

require 'json'
out=JSON.parse(input)

This will return a Hash

这将返回一个散列。

#7


5  

require 'json'

hash = JSON.parse string

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

处理好散列,做你想做的事情。

#8


2  

The Oj gem (https://github.com/ohler55/oj) should work. It's simple and fast.

应该使用Oj gem (https://github.com/ohler55/oj)。很简单和快速。

http://www.ohler.com/oj/#Simple_JSON_Writing_and_Parsing_Example

http://www.ohler.com/oj/ Simple_JSON_Writing_and_Parsing_Example

require 'oj'

h = { 'one' => 1, 'array' => [ true, false ] }
json = Oj.dump(h)

# json =
# {
#   "one":1,
#   "array":[
#     true,
#     false
#   ]
# }

h2 = Oj.load(json)
puts "Same? #{h == h2}"
# true

The Oj gem won't work for JRuby. For JRuby this (https://github.com/ralfstx/minimal-json) or this (https://github.com/clojure/data.json) may be good options.

Oj gem不会为JRuby工作。对于JRuby来说(https://github.com/ralfstx/minimal-json)或这个(https://github.com/clojure/data.json)可能是不错的选择。

#9


2  

RUBY is case sensitive.

RUBY是区分大小写的。

require 'json' # json must be lower case

JSON.parse(<json object>)  

for example

例如

JSON.parse(response.body) # JSON must be all upper-case

#10


1  

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:

如果你知道源url,你可以使用:

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:

如果您不知道源url的关键字,您可以执行以下操作:

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.

如果您担心JSON结构可能会发生变化,那么您可以构建一个简单的JSON模式,并在尝试访问密钥之前验证JSON。这将提供一个守卫。

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

注意:必须轧轧钻头。由于张贴规则,ly url。

#11


0  

Ruby has a JSON parser:

Ruby有一个JSON解析器:

require 'json'

#12


0  

This can be done as below, just need to use JSON.parse, then you can traverse through it normally with indices.

可以这样做,只需要使用JSON。解析,然后你可以通过索引来遍历它。

#ideally not really needed, but in case if JSON.parse is not identifiable in your module  
require 'json'

#Assuming data from bitly api is stored in json_data here

json_data = '{
  "errorCode": 0,
  "errorMessage": "",
  "results":
  {
    "http://www.foo.com":
    {
       "hash": "e5TEd",
       "shortKeywordUrl": "",
       "shortUrl": "http://whateverurl",
       "userHash": "1a0p8G"
    }
  },
  "statusCode": "OK"
}'

final_data = JSON.parse(json_data)
puts final_data["results"]["http://www.foo.com"]["shortUrl"]

#13


-2  

You can try something like this:

你可以试试这样的方法:

def details_to_json
{
  :id                    => self.id, 
  :credit_period_type    => self.credit_period_type,
  :credit_payment_period => self.credit_payment_period,

 }.to_json
end

#1


410  

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

Rails应该自动为您加载json模块,因此不需要添加“json”。

#2


179  

Parsing JSON in Rails is quite straightforward:

在Rails中解析JSON非常简单:

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:

让我们假设,您想要将shortUrl与一个站点对象关联的对象,它有两个属性——short_url和long_url。要得到shortUrl并将其与适当的站点对象关联起来,您可以这样做:

parsed_json["results"].each do |longUrl, convertedUrl|
  site = Site.find_by_long_url(longUrl)
  site.short_url = convertedUrl["shortUrl"]
  site.save
end

#3


53  

This answer is quite old. pguardiario's got it.

这个答案相当古老。pguardiario有它。

One site to check out is JSON implementation for Ruby. This site offers a gem you can install for a much faster C extension variant.

要检查的一个站点是Ruby的JSON实现。这个站点提供了一个gem,您可以安装一个更快的C扩展变种。

With the benchmarks given their documentation page they claim that it is 21.500x faster than ActiveSupport::JSON.decode

根据他们的文档页面,他们声称它比ActiveSupport::JSON.decode快了21.500x。

The code would be the same as Milan Novota's answer with this gem, but the parsing would just be:

这段代码与米兰·诺沃塔(Milan Novota)用这颗宝石的答案是一样的,但解析只是:

parsed_json = JSON(your_json_string)

#4


18  

Here is an update for 2013.

以下是2013年的最新情况。

Ruby

Ruby 1.9 has a default JSON gem with C extensions. You can use it with

Ruby 1.9有一个带有C扩展的默认JSON gem。你可以用它。

require 'json'
JSON.parse ''{ "x": "y" }'
# => {"x"=>"y"}

The parse! variant can be used for safe sources. There are also other gems, which may be faster than the default implementation. Please refer to multi_json for the list.

解析!变体可用于安全的来源。还有其他的gem,它可能比默认的实现快。请参考列表的multi_json。

Rails

Modern versions of Rails use multi_json, a gem that automatically uses the fastest JSON gem available. Thus, the recommended way is to use

Rails的现代版本使用multi_json,这是一种自动使用最快的JSON gem的gem。因此,推荐的方法是使用。

object = ActiveSupport::JSON.decode json_string

Please refer to ActiveSupport::JSON for more information. In particular, the important line in the method source is

请参考ActiveSupport::JSON以获取更多信息。特别地,方法源中的重要行是。

data = MultiJson.load(json, options)

Then in your Gemfile, include the gems you want to use. For example,

然后在你的Gemfile中,包括你想要使用的宝石。例如,

group :production do
  gem 'oj'
end

#5


7  

Ruby's bundled JSON is capable of exhibiting a bit of magic on its own.

Ruby的绑定JSON可以自己显示一点魔法。

If you have a string containing JSON serialized data that you want to parse:

如果您有一个包含JSON序列化数据的字符串,您需要解析:

JSON[string_to_parse]

JSON will look at the parameter, see it's a String and try decoding it.

JSON会查看参数,看它是一个字符串并尝试解码它。

Similarly, if you have a hash or array you want serialized, use:

类似地,如果您想要序列化的散列或数组,请使用:

JSON[array_of_values]

Or:

或者:

JSON[hash_of_values]

And JSON will serialize it. You can also use the to_json method if you want to avoid the visual similarity of the [] method.

JSON会序列化它。如果希望避免[]方法的视觉相似性,也可以使用to_json方法。

Here are some examples:

下面是一些例子:

hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]

JSON[hash_of_values] 
# => "{\"foo\":1,\"bar\":2}"

JSON[array_of_values] 
# => "[{\"foo\":1,\"bar\":2}]"

string_to_parse = array_of_values.to_json
JSON[string_to_parse]
# => [{"foo"=>1, "bar"=>2}]

If you root around in JSON you might notice it's a subset of YAML, and, actually the YAML parser is what's handling JSON. You can do this too:

如果你在JSON中找到根,你可能会注意到它是YAML的一个子集,实际上YAML解析器是处理JSON的。你也可以这样做:

require 'yaml'

YAML.load(string_to_parse)
# => [{"foo"=>1, "bar"=>2}]

If your app is parsing both YAML and JSON, you can let YAML handle both flavors of serialized data.

如果您的应用程序正在解析YAML和JSON,您可以让YAML处理两种类型的序列化数据。

#6


5  

require 'json'
out=JSON.parse(input)

This will return a Hash

这将返回一个散列。

#7


5  

require 'json'

hash = JSON.parse string

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

处理好散列,做你想做的事情。

#8


2  

The Oj gem (https://github.com/ohler55/oj) should work. It's simple and fast.

应该使用Oj gem (https://github.com/ohler55/oj)。很简单和快速。

http://www.ohler.com/oj/#Simple_JSON_Writing_and_Parsing_Example

http://www.ohler.com/oj/ Simple_JSON_Writing_and_Parsing_Example

require 'oj'

h = { 'one' => 1, 'array' => [ true, false ] }
json = Oj.dump(h)

# json =
# {
#   "one":1,
#   "array":[
#     true,
#     false
#   ]
# }

h2 = Oj.load(json)
puts "Same? #{h == h2}"
# true

The Oj gem won't work for JRuby. For JRuby this (https://github.com/ralfstx/minimal-json) or this (https://github.com/clojure/data.json) may be good options.

Oj gem不会为JRuby工作。对于JRuby来说(https://github.com/ralfstx/minimal-json)或这个(https://github.com/clojure/data.json)可能是不错的选择。

#9


2  

RUBY is case sensitive.

RUBY是区分大小写的。

require 'json' # json must be lower case

JSON.parse(<json object>)  

for example

例如

JSON.parse(response.body) # JSON must be all upper-case

#10


1  

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:

如果你知道源url,你可以使用:

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:

如果您不知道源url的关键字,您可以执行以下操作:

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.

如果您担心JSON结构可能会发生变化,那么您可以构建一个简单的JSON模式,并在尝试访问密钥之前验证JSON。这将提供一个守卫。

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

注意:必须轧轧钻头。由于张贴规则,ly url。

#11


0  

Ruby has a JSON parser:

Ruby有一个JSON解析器:

require 'json'

#12


0  

This can be done as below, just need to use JSON.parse, then you can traverse through it normally with indices.

可以这样做,只需要使用JSON。解析,然后你可以通过索引来遍历它。

#ideally not really needed, but in case if JSON.parse is not identifiable in your module  
require 'json'

#Assuming data from bitly api is stored in json_data here

json_data = '{
  "errorCode": 0,
  "errorMessage": "",
  "results":
  {
    "http://www.foo.com":
    {
       "hash": "e5TEd",
       "shortKeywordUrl": "",
       "shortUrl": "http://whateverurl",
       "userHash": "1a0p8G"
    }
  },
  "statusCode": "OK"
}'

final_data = JSON.parse(json_data)
puts final_data["results"]["http://www.foo.com"]["shortUrl"]

#13


-2  

You can try something like this:

你可以试试这样的方法:

def details_to_json
{
  :id                    => self.id, 
  :credit_period_type    => self.credit_period_type,
  :credit_payment_period => self.credit_payment_period,

 }.to_json
end