4

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]

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

1 Comment

thx it seems work, if one of the item doesn't not contain ["name"], how can I guard that as well?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.