访问嵌套在数组中的JSON哈希元素

时间:2017-01-27 17:09:39

标签: json ruby

我试图引用具有相同键名的字符串,但希望打印第二个键值。例如:

text = '[{ "name": "car",  "status": "good" },
         { "name": "bus",  "status": "bad" },
         { "name": "taxi", "status": "soso" }]'

我想转到第二个元素的name

1 个答案:

答案 0 :(得分:1)

require 'json'
text = '[{ "name" : "car", "status": "good"}, { "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"}]' # Note change to single outer quotes
puts JSON.load(text)[1]["name"]
# => bus

因为text在技术上是一个哈希数组,你想获得索引值[1],然后查看哈希键[“名称”]