我正在使用coinbase API获取每个帐户的接收地址列表,然后我将其解析为JSON。但是,我想在网页上显示这些JSON元素。在我这样做的时候,我将如何遍历JSON数组并生成html(例如,在每个元素之后附加
,以使每个元素都在不同的行上)?
json对象在下面,我想打印出一个“地址”属性列表:
{"addresses":[{"address":
{"address":"1JdB88wMbd9u63rHkReuCLxaGEweaUydGA","callback_url":null,"label":null,"created_at":"2014-08-14T18:17:17-07:00"}},
{"address":{"address":"1MoaCahENJvTAnHrUUW3VgHHQd3yLzVv9G","callback_url":null,"label":null,"created_at":"2014-08-14T01:04:08-07:00"}},
{"address":{"address":"155KDpZrQN4wmMHV7ypC9ZV1fLeLdSEFAc","callback_url":null,"label":null,"created_at":"2014-08-14T01:04:06-07:00"}},
{"address":{"address":"18c6WUcgo5gJVj6QgpnH5ZX5aBhHpWSLYv","callback_url":null,"label":null,"created_at":"2014-06-19T17:28:04-07:00"}}],
"total_count":4,"num_pages":1,"current_page":1}
答案 0 :(得分:2)
您必须将json(JSON Doc)解析为哈希:
require 'json'
json_response = "{\"addresses\":[{\"address\":\n{\"address\":\"1JdB88wMbd9u63rHkReuCLxaGEweaUydGA\",\"callback_url\":null,\"label\":null,\"created_at\":\"2014-08-14T18:17:17-07:00\"}},\n{\"address\":{\"address\":\"1MoaCahENJvTAnHrUUW3VgHHQd3yLzVv9G\",\"callback_url\":null,\"label\":null,\"created_at\":\"2014-08-14T01:04:08-07:00\"}},\n{\"address\":{\"address\":\"155KDpZrQN4wmMHV7ypC9ZV1fLeLdSEFAc\",\"callback_url\":null,\"label\":null,\"created_at\":\"2014-08-14T01:04:06-07:00\"}},\n{\"address\":{\"address\":\"18c6WUcgo5gJVj6QgpnH5ZX5aBhHpWSLYv\",\"callback_url\":null,\"label\":null,\"created_at\":\"2014-06-19T17:28:04-07:00\"}}],\n\"total_count\":4,\"num_pages\":1,\"current_page\":1}"
hash_response = JSON.parse(json_response)
@addresses = hash_response['addresses']
然后在你看来,只需迭代地址:
<ul>
<% @addresses.each do |address| %>
<li>= address['address']['address'] </li>
<% end %>
</ul>