简体   繁体   中英

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

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

您可以在另一行代码中完成另一种方法;)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM