Ruby: How can I get all the key elements from the json format?

I'm new to ruby, I don't look like a block of code ... How can I get the whole key element in json text format?

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

From the text, this is a string with a json-like format, as I can only extract the name and enter into an array

desired result ==> [car, bus, taxi]

+3
source share
1 answer

First you need to parse the JSON data:

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 elements:

p data.collect { |item| item['name'] }

If you do not have a name for each element and you want to use the default value:

p data.collect { |item| item.fetch('name', 'default value') }

If you want to just skip them:

p data.collect { |item| item['name'] }.compact
+10
source

All Articles