我是 ruby 新手,我不熟悉代码块... 如何获取json格式文本中的所有关键元素?
text= "[{ "name" : "car", "status": "good"},
{ "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"}]"
从文本来看,是一个类似json格式的字符串, 如何仅提取名称值并输入到数组中
期望的输出==> [汽车、公共(public)汽车、出租车]
最佳答案
首先需要解析JSON数据:
require('json')
text = '[{ "name" : "car", "status": "good"}, { "name" : "bus", "status": "bad"},{ "name" : "taxi", "status": "soso"}]'
data = JSON.parse(text)
然后你可以简单地收集元素:
p data.collect { |item| item['name'] }
如果您没有每个项目的名称并且您想要一个默认值:
p data.collect { |item| item.fetch('name', 'default value') }
如果你想跳过它们:
p data.collect { |item| item['name'] }.compact
关于Ruby:如何从 json 格式中获取所有关键元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10511972/