如何使用 Ruby on Rails 解析 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1826727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:00:54  来源:igfitidea点击:

How do I parse JSON with Ruby on Rails?

ruby-on-railsrubyjson

提问by Dan Sinker

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 shortUrlfrom the JSON returned from the bit.ly API:

具体来说,我正在寻找的是一种shortUrl从 bit.ly API 返回的 JSON 中提取的方法:

{
  "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 写入与长 URL 关联的 ActiveRecord 对象中。

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.

这是我可以完全在概念上思考的事情之一,当我坐下来执行时,我意识到我有很多东西要学。

回答by pguardiario

These answers are a bit dated. Therefore I give you:

这些答案有点过时了。因此我给你:

hash = JSON.parse string

Rails should automagically load the jsonmodule for you, so you don'tneed to add require 'json'.

Rails的应该会自动加载json模块你,所以你不做需要添加require 'json'

回答by Milan Novota

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 关联的对象是一个 Site 对象,它有两个属性 - short_url 和 long_url。然后,要获取 shortUrl 并将其与适当的 Site 对象关联,您可以执行以下操作:

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

回答by lillq

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 pagethey claim that it is 21.500xfaster than ActiveSupport::JSON.decode

基准测试给出了他们的文档页面,他们声称它比基准21.500ActiveSupport::JSON.decode

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

代码与 Milan Novota 对此 gem 的回答相同,但解析将是:

parsed_json = JSON(your_json_string)

回答by James Lim

Here is an update for 2013.

这是 2013 年的更新。

Ruby

红宝石

Ruby 1.9 has a default JSON gemwith 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 safesources. There are also other gems, which may be faster than the default implementation. Please refer to multi_jsonfor the list.

parse!变体可用于安全来源。还有其他 gems,它们可能比默认实现更快。请参考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::JSONfor 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 中,包含您要使用的 gem。例如,

group :production do
  gem 'oj'
end

回答by the Tin Man

Ruby's bundled JSONis 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_jsonmethod 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 处理这两种类型的序列化数据。

回答by user2726667

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

This will return a Hash

这将返回一个哈希

回答by Mohammad Shahadat Hossain

require 'json'

hash = JSON.parse string

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

使用哈希并做你想做的事。

回答by Nishant Rawat

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

这可以按如下方式完成,只需要使用JSON.parse,然后您就可以使用索引正常遍历它。

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

回答by Steven

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

回答by Dom

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:

如果您不知道源 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.

注意:由于发布规则,不得不修改 bit.ly url。