在Ruby中提取所需的JSON标记

时间:2015-10-14 08:52:10

标签: html ruby json

我从json的网站上提取了数据,看起来有点像这样:

    {
        "results": [
            {
                "image": "http://en.hdyo.org/assets/art-shutter-young-people-a12e2c0cd7a54920cb024fd1394190fd.jpg",
                "tags": [
                    {
                        "confidence": 39.00159782165525,
                        "tag": "people"
                    },
                    {
                        "confidence": 35.583618780278364,
                        "tag": "happy"
                    },
                    {
                        "confidence": 34.44308639680471,
                        "tag": "group"
                    },
                    {
                        "confidence": 33.77196537562902,
                        "tag": "man"
                    },
                    {
                        "confidence": 32.55533432893469,
                        "tag": "smiling"
                    }
                ]
            }
        ]
    }

有没有办法提取所有confidence分数和tags

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

results = web_data.scan(/(tag\s\S*\stag)/).flatten
# => ["tag 'A' tag", "tag 'B' tag", "tag 'C' tag", "tag 'D' tag", "tag 'E' tag"]

这是你想要的吗?

<强>更新

require 'json'
json_data = JSON.parse(web_data)

keys   = ['tag']
values = json_data['results'].map do |result|
  result['tags'].map do |tag|
    tag.values_at(*keys)
  end
end

# values => [[["people"], ["happy"], ["group"], ["man"], ["smiling"], ["smile"], ["person"]]]