user1735921
user1735921

Reputation: 1389

Rails: fastest function to extract json field and convert to array

I have a json object as follows which is the input.

[
{"feild1":"val11","field2":"val12"},
{"feild1":"val21","field2":"val22"},
{"feild1":"val31","field2":"val32"}
]

I want output in an array object for only feild1, as follows:

array_for_feild_one =  ["val11", "val21", "val31"]

I know I can loop through the whole json object, but then I don't see the point of JSON object, whats the use of keys and values when I have to use a loop in the end, isn't there a better way ?

So far I have tried this:

json_obj.each do |obj|

    my_array << obj['field1']
end

edit:

Complete code is as follows:

json_obj = JSON.parse('[
{"feild1":"val11","field2":"val12"},
{"feild1":"val21","field2":"val22"},
{"feild1":"val31","field2":"val32"}
]')
my_array = []
json_obj.each do |obj| 
        my_array << obj['field1']
end
puts my_array.inspect

Upvotes: 0

Views: 212

Answers (2)

Qubaish Bhatti
Qubaish Bhatti

Reputation: 728

There is an alternate way you can do it in single line of code ;)

ActiveSupport::JSON.decode(your_json).map{|a| a["feild1"]}

Upvotes: 1

Vishal Jain
Vishal Jain

Reputation: 1940

you can try following way using collect method in ruby:

json_obj = JSON.parse('[
{"feild1":"val11","field2":"val12"},
{"feild1":"val21","field2":"val22"},
{"feild1":"val31","field2":"val32"}
]')
my_array = json_obj.collect{|a| a["feild1"]}
puts my_array.inspect

Upvotes: 1

Related Questions