[英]Ruby: How can I get all the key elements from an json format?
I am new on ruby, i am not faimilar with the code block... How can I get all the key element in an json format text? 我是ruby的新手,我与代码块并不相似......我怎样才能获得json格式文本中的所有关键元素?
text= "[{ "name" : "car", "status": "good"},
{ "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"}]"
From the text, it is a string with json like format, how can i extract the name value only and input into an array 从文本中,它是一个json格式的字符串,如何只提取名称值并输入到数组中
desired output ==> [car, bus, taxi] 期望的输出==> [汽车,公共汽车,出租车]
You need to parse the JSON data first: 您需要首先解析JSON数据:
require('json')
text = '[{ "name" : "car", "status": "good"}, { "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"}]'
data = JSON.parse(text)
Then you can simply collect the items: 然后你可以简单地收集物品:
p data.collect { |item| item['name'] }
If you don't have name for every item and you want a default value instead: 如果您没有每个项目的名称,而您想要一个默认值:
p data.collect { |item| item.fetch('name', 'default value') }
If you want just skip them: 如果你想跳过它们:
p data.collect { |item| item['name'] }.compact
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.