【问题标题】:rails render extract value from json responserails render 从json响应中提取值
【发布时间】:2014-07-10 17:38:13
【问题描述】:

我有一个 Rails 应用程序,我正在尝试从解析的 JSON 哈希中呈现一组项目。

我当前的渲染语句如下所示

resp = JSON.parse(response.body)
render json: resp

我正在使用 Typheous,但这段代码对我不起作用:

resp = JSON.parse(response.body).fetch("item")

以下是 JSON 哈希(item 键有很多值,但为了简洁我只显示一个):

{
  ebay: [{
    findItemsByKeywordsResponse: [{
      ack: [],
      version: [],
      timestamp: [],
      searchResult: [{
        count: "91",
        item: [{
          itemId: [ "321453454731" ]
        }]
      }]
    }]
  }]
}

如何从解析的 JSON 哈希中呈现一组项目?

【问题讨论】:

  • findItemsByKeywordsResponsesearchResult 键是否有多个值?如果是这样,您将不得不遍历每个键以缩小到 item 数组。例如,使用发布的哈希,为了获得单个 item 的数组,你需要这样的东西:resp[:ebay].first[:findItemsByKeywordsResponse].first[:searchResult].first[:item],这将产生 {:itemId=>["321453454731"]}
  • 不,ebay 和 findItemsKeywordsResponse 只有一个值,我需要整个项目列表/数组

标签: ruby-on-rails json typhoeus


【解决方案1】:

由于 ebayfindItemsByKeywordsResponse 键只有一个值(根据 OP 的评论),您可以通过执行以下操作来检索 items 数组:

resp = JSON.parse(response.body)
resp[:ebay].first[:findItemsByKeywordsResponse].first[:searchResult].first[:item]

这将为您提供一个包含 itemId 和任何其他键值对的哈希数组。

您想要包含.first(或[0])的原因是因为基于解析的JSON响应,您的哈希包含一个哈希数组,一直嵌套到item数组。如果有多个 searchResult 值,则需要在获取 item 数组之前遍历这些值。

【讨论】:

  • 感谢您的解释很有帮助。这对我有用 render json: resp["findItemsByKeywordsResponse"].first["searchResult"].first["item"] 并渲染 json: resp.first["findItemsByKeywordsResponse"].first["searchResult"].first[" item"] 目前不工作,不知道为什么
  • 不客气。如果resp.first... 不起作用,则仅表示resp 中的first 对象没有findItemsByKeywordsResponse 键。您可以inspect 或打印解析的 JSON 响应以查看其完整结构以及它将响应哪些键。
猜你喜欢
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 2022-07-02
  • 2020-07-28
相关资源
最近更新 更多