简体   繁体   English

遍历Rails5中的JSON数组

[英]Iterate over JSON Array in Rails5

I know I am missing something probably very obvious. 我知道我可能遗漏了一些非常明显的东西。 I am trying to iterate over a JSON array in my Rails5 view. 我正在尝试在Rails5视图中遍历JSON数组。 I tried several things but can't seem to get the proper items to render. 我尝试了几件事,但似乎无法获得合适的项目进行渲染。 The below code renders {"name"=>"Large Plaque", "price"=>"2500"} {"name"=>"Small Plaque", "price"=>"1500"} to my view. 下面的代码将{"name"=>"Large Plaque", "price"=>"2500"} {"name"=>"Small Plaque", "price"=>"1500"}呈现给我。

config/plaque_data.json 配置/ plaque_data.json

{
  "products": [
    {
      "name": "Large Plaque",
      "price": "2500"
    },
    {
      "name": "Small Plaque",
      "price": "1500"
    }
  ]
}

controllers/plaqueorders_controller.rb 控制器/ plaqueorders_controller.rb

...
def new
 @plaqy = JSON.load File.read('config/plaque_data.json')
end
...

views/plaqueorders/new.html.erb 视图/ plaqueorders / new.html.erb

...
<% @plaqy['products'].each do |k, v| { name: k, price: v } %>
 <%= k %>
<% end %>
...

Since 'k' is a hash, you need to access k['name'] and k['price'] to extract price and name. 由于“ k”是一个哈希,因此您需要访问k ['name']和k ['price']以提取价格和名称。

Also when you use .each on an array, you normally only declare one block argument (You have two, k and v ). 同样,在数组上使用.each时,通常只声明一个块参数(您有两个k和v)。

You normally write 2 block arguments for Hashes (and lots of other Enumerable methods), which is possibly what you thought you were iterating over, but 通常,您为哈希(和许多其他Enumerable方法)编写2个块参数,这可能是您认为要迭代的内容,但是

@plaqy['products']

is an array 是一个数组

Just to expand on the above answer, in your view you are iterating over an array, but treating it like a hash. 只是为了扩展上述答案,您认为您正在遍历数组,但将其视为哈希。 So you might want to change your view to something like: 因此,您可能需要将视图更改为以下内容:

views/plaqueorders/new.html.erb 视图/ plaqueorders / new.html.erb

...
<% @plaqy['products'].each do |product|%>
 Name: <%= product['name'] %>
 Price: $<%= product['price'] %>
<% end %>
...

Obviously the block will change based on how you want to render each product, but something like that will work. 显然,该块将根据您要呈现每种产品的方式而变化,但是类似的方法将起作用。

If you want to loop over the hashes because you don't know what the shape is (strange but okay), you'd want something like 如果您由于不知道形状是什么(奇怪但可以)而想要遍历散列,则需要类似

...
<% @plaqy['products'].each do |product|%>
 <% product.each do |key, value| %>
   <%= key %>: <%= value %>
 <% end %>
<% end %>
...

Naming the variables of an each loop k, v is generally reserved for hashes. 命名每个循环k的变量时,通常为哈希保留v。 But in your code, the k wasn't the key of the hash but rather each individual product. 但是在您的代码中,k不是哈希键,而是每个单独的乘积。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM