【问题标题】:Accessing certain values in nested JSON response from API [closed]从 API 访问嵌套 JSON 响应中的某些值 [关闭]
【发布时间】:2020-03-22 02:55:01
【问题描述】:

我目前正在从外部 API 获取数据,并且能够显示一些数据。但是我希望能够访问某些数据,但不确定如何获取所有数据。这是我从 API 获得的 JSON 响应的 sn-p。

hits":[10 items
  0:{3 items
  "recipe":{...}18 items
  "bookmarked":false
  "bought":false
  }
    1:{3 items
    "recipe":{18 items
    "uri":"http://www.edamam.com/ontologies/edamam.owl#recipe_8275bb28647abcedef0baaf2dcf34f8b"
    "label":"Chicken Paprikash"
    "image":"https://www.edamam.com/web-img/e12/e12b8c5581226d7639168f41d126f2ff.jpg"
    "source":"No Recipes"
    "url":"http://norecipes.com/recipe/chicken-paprikash/"
    "shareAs":"http://www.edamam.com/recipe/chicken-paprikash-8275bb28647abcedef0baaf2dcf34f8b/chicken"
    "yield":4
    "dietLabels":[...]1 item
    "healthLabels":[...]3 items
    "cautions":[...]2 items
    "ingredientLines":[...]11 items
    "ingredients":[12 items
       0:{2 items
       "text":"640 grams chicken - drumsticks and thighs ( 3 whole chicken legs cut apart)"
       "weight":640
       }
       1:{2 items
      "text":"640 grams chicken - drumsticks and thighs ( 3 whole chicken legs cut apart)"
      "weight":640
      }
      2:{2 items
      "text":"1/2 teaspoon salt"
      "weight":3
      }

我想访问所有“成分”数组中的“文本”。现在要显示我正在做的数据:


<% @recipe.each do |r| %>
<img src=<%= r["recipe"]["image"] %> class="card-img-top" alt="...">
  <div class="card-body">
    <h8 class ="title", style = "text-align: center;"><%= r["recipe"]["label"] %></h8>
    <h8><%= r["recipe"]["dietLabels"] %></h8>
    </br>
    <ul>
    <li><h8 class="card-title"><h8><%= r["recipe"]["ingredients"][0]["text"] %></h8></li>

    </ul>
<% end %>

这可行,但正如您所见,我只在索引 0 处获取每种成分中的文本。有没有办法让我获取所有文本,因为在 JSON 响应中有很多餐点,并且都有不同数量的成分所以单独输入每个索引是行不通的。有什么建议吗?

【问题讨论】:

  • 不要提供 JSON 的“sn-p”。 JSON 是一个序列化形式的对象,所以如果没有完整的流,我们就会得到一个不偏不倚的对象,然后我们不得不对其进行更改,从而导致我们的答案有些摇摆不定。请参阅“How to Ask”、“Stack Overflow question checklist”和“MCVE”及其所有链接页面。

标签: ruby-on-rails json ruby api


【解决方案1】:

在你的视图中试试这个

<% @ingredients = r["recipe"]["ingredients"] %>
<ul>
  <% @ingredients.each do |ingredient| %>
    <li><h8 class="card-title"><%= ingredient['text'] %><h8></h8></li>
  <% end %>
</ul>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 2018-09-12
  • 2020-08-19
  • 1970-01-01
  • 2016-07-23
相关资源
最近更新 更多