1

可能重复:
在 ruby​​ 中解析 JSON 字符串

我已经设法通过 JSON gem 和以下代码将一堆 json 放入 ruby​​ 中的变量并打印出来:

require 'open-uri'
require 'json'

result = JSON.parse(open("https://api.pinboard.in/v1/posts/get?auth_token=username:token&tag=fashion&meta=yes&format=json").read)
puts result

它返回的是这样的:

{
  "date"=>"2012-09-24T03:35:38Z",
  "user"=>"username",
  "posts"=>[{
      "href"=>"http://example.com/example.jpg",
      "description"=>"this is the description",
      "extended"=>"A full, longer description.",
      "meta"=>"d6f967c9adfbe1eb3763fddbcd993d1b",
      "hash"=>"a46e0e7202d9d56c516a472d8be70d9e",
      "time"=>"2012-09-24T03:35:38Z",
      "shared"=>"yes",
      "toread"=>"no",
      "tags"=>"fashion"
    }
]}

(为了清楚起见,这里的行距是我的)

我的问题是,我不知道如何访问这些键和值!我已经用谷歌搜索过,但我对 ruby​​ 真的很陌生,而且我在弄清楚我应该做什么时遇到了很多麻烦,更不用说代码来做这件事了帮助?

4

2 回答 2

2

result["date"] - accesses the date key on the json.

In general result[<key>] accesses the value stored in key.

If you try to access a key that does not exists you will get nil as a result.

Edit: In order to traverse the key/value pairs you can:

result.each do |key, value|
   puts "result[#{key}] = #{value}"
end
于 2012-09-24T15:01:13.553 回答
0

Do stuff like:

p result["date"]
p result["posts"].size

Look up the documentation for the ruby Array and Hash classes.

于 2012-09-24T15:00:24.723 回答