2014-07-10 135 views
1

我有一个Rails应用程序,我试图从解析的JSON哈希渲染项目数组。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散列的项目数组?

+0

“findItemsByKeywordsResponse”和“searchResult'键有多少值?如果是这样,你必须迭代每个键来缩小到'item'数组。例如,使用发布的散列,为了获得单个'item'的数组,你需要像这样的:'resp [:ebay] .first [:findItemsByKeywordsResponse] .first [:searchResult] .first [ :item]',这将产生'{:itemId => [“321453454731”]}' – mmichael

+0

不,只有一个eBay价值和findItemsKeywordsResponse我需要整个项目列表/数组 – Rigel

回答

1

由于对于ebayfindItemsByKeywordsResponse键只有一个值(每OP的评论),你可以做这样的事情检索items数组:

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

这会给你的数组包含itemId和任何其他键 - 值对的散列。

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

+0

谢谢解释是有帮助的。这对我来说渲染json:resp [“findItemsByKeywordsResponse”]。first [“searchResult”]。first [“item”] and render json:resp.first [“findItemsByKeywordsResponse”]。first [“searchResult”]。first [“项目“]不起作用截至目前不知道为什么 – Rigel

+0

不客气。如果'resp.first ...'不起作用,这意味着'resp'中的'first'对象没有'findItemsByKeywordsResponse'键。您可以“检查”或打印解析的JSON响应以查看其完整结构以及它将响应哪些键。 – mmichael