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

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

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

然后把那个短URL写进一个与长URL相关的ActiveRecord对象。

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


当前回答

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

hash = JSON.parse string

Rails会自动为你加载json模块,所以你不需要添加require 'json'。

其他回答

橙汁宝石(https://github.com/ohler55/oj)应该工作。它简单快捷。

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

Oj宝石对JRuby不起作用。对于JRuby, this (https://github.com/ralfstx/minimal-json)或this (https://github.com/clojure/data.json)可能是不错的选择。

RUBY区分大小写。

require 'json' # json must be lower case

JSON.parse(<json object>)  

例如

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

我会这么做:

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]

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

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

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

如果你不知道源url的键,你可以这样做:

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

如果你不想使用符号查找键,你可以将散列中的键转换为字符串:

results = json[:results].stringify_keys

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

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

注意:钻头必须破损。因为发布规则,Ly url。

以下是2013年的最新情况。

Ruby

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

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

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

Rails

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

object = ActiveSupport::JSON.decode json_string

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

data = MultiJson.load(json, options)

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

group :production do
  gem 'oj'
end

你可以尝试这样做:

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

 }.to_json
end