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?
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
desired output ==> [car, bus, taxi]
You need to parse the JSON data first:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With