访问深层嵌套数组中的值 - Ruby on Rails

时间:2017-07-08 00:26:49

标签: ruby-on-rails arrays json ruby rails-api

我正在使用API​​调用返回JSON响应。我想访问响应中的数据,这样我就可以创建一些显示信息和图片的漂亮显示卡。这是响应的一个片段,响应属性填充了大约20个对象,为简洁起见我只包括两个:

{
    "success": true,
    "message": "",
    "result": [
        {
            "MarketCurrency": "LTC",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Litecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-LTC",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/R29q3dD.png"
        },
        {
            "MarketCurrency": "DOGE",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Dogecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-DOGE",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
        },

在我的Rails控制器中,我正在使用JSON.parse,我正在尝试将其转换为具有Open struct选项的对象:

@markets = JSON.parse(markets.to_json, object_class: OpenStruct)

在我的视图中,我将执行此操作<%=@markets.class%>并显示数组而非对象。所以我试试这个<%=@markets.size%>并显示1.如果我做<%=@markets[0]['success']%>我希望它返回true但它返回'success'。所以,我不明白为什么ostruct库没有像我期望的那样工作,或者我怎么能找到存储在结果数组中的对象。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

您已经有了JSON响应,不需要再次使用to_json,尝试解析该对象,然后使用点.访问其字段,作为OpenStruct对象现在,您可以将它们作为方法访问:

require 'json'

a = '{
  "success": true,
  "message": "",
  "result": [{
    "MarketCurrency": "LTC",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Litecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-LTC",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/R29q3dD.png"
  }, {
    "MarketCurrency": "DOGE",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Dogecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-DOGE",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
  }]
}'

b = JSON.parse(a, object_class: OpenStruct)
p b.success
# => true

答案 1 :(得分:1)

经过大量调试和一些帮助后,我才能让它发挥作用。 API调用的响应是一个包含一个项目的数组。该项是整个数据集的长字符串。

为了获得&#34; true&#34;的预期行为在致电@ markets.success时,我首先必须

raw_markets = JSON.parse(markets.to_json)

接着是

@markets = raw_markets.map do |market|
      JSON.parse(market, object_class: OpenStruct)

注意:可变市场持有最初的api电话:

markets = open('url-to-api')

在此之后,我会得到@ markets.success =&#34; true&#34;和@ markets.result [0]举行了第一个结果,@ markets.result [1]举行了第二个结果,依此类推。