Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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]

like image 942
TheOneTeam Avatar asked Dec 13 '22 02:12

TheOneTeam


1 Answers

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
like image 74
KARASZI István Avatar answered Jun 06 '23 21:06

KARASZI István