从 JSON 嵌套哈希中提取特定字段



我正在考虑编写一个 Web 应用程序来抓取 API 并以 JSON 形式返回此信息。

但是,我只在一个数字之后,然后是当前价格(在此示例中为"227")。如何在 Ruby 中访问它? 我不知道从哪里开始。我从未处理过这样的文本。

为了讨论起见,假设我将此输出保存到实例变量中@information

{
    "item": {
        "icon": "http://services.runescape.com/m=itemdb_rs/4332_obj_sprite.gif?id=4798",
        "icon_large": "http://services.runescape.com/m=itemdb_rs/4332_obj_big.gif?id=4798",
        "id": 4798,
        "type": "Ammo",
        "typeIcon": "http://www.runescape.com/img/categories/Ammo",
        "name": "Adamant brutal",
        "description": "Blunt adamantite arrow...ouch",
        "current": {
            "trend": "neutral",
            "price": 227
        },
        "today": {
            "trend": "neutral",
            "price": 0
        },
        "day30": {
            "trend": "positive",
            "change": "+1.0%"
        },
        "day90": {
            "trend": "positive",
            "change": "+1.0%"
        },
        "day180": {
            "trend": "positive",
            "change": "+2.0%"
        },
        "members": "true"
    }
}

首先按照这篇文章将这个JSON解析为哈希在 Ruby 中解析 JSON 字符串

假设解析的哈希名称是my_hash那么以下内容应该给你价格

my_hash['item']['current']['price']

编辑:

正如您所说,您想将其保存在@information

@information = my_hash['item']['current']['price']

即使你可以使用hashie,它也把你的json变成可读的结构代码

安装哈希

gem install hashie

然后在您的代码中,JSON 接收的所有变量my_json

myhash = Hashie::Mash.new(my_json)

@information = my_hash.item.current.price

技巧:-如果您的 JSON 是动态的,并且它可能会响应其他一些结构元素,因此您可以维护异常代码

@information = my_hash.item.try(:current).try(:price)

最新更新