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

2024-02-06

我正在考虑编写一个 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 in to Hash 在 Ruby 中解析 JSON 字符串 https://stackoverflow.com/questions/5410682/parsing-a-json-string-in-ruby

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

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

Edit:

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

@information = my_hash['item']['current']['price']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 JSON 嵌套哈希中提取特定字段 的相关文章

随机推荐