Jack Mackonney Jack Mackonney - 1 year ago 64
JSON Question

How to get index of an object in JSON array?

I have JSON array with the format below, how can I get the position (index) of an object using its key?

json = [
{
"id"=>1,
"user_name"=>"Mean Dean",
"user_profile_id"=>"1",
"amount"=>4
},
{
"id"=>2,
"user_name"=>"Mad Stan",
"user_profile_id"=>"2",
"amount"=>7
},
{
"id"=>3,
"user_name"=>"Jack Dean",
"user_profile_id"=>"3",
"amount"=>8
}
]


For example how would I go about it if I wanted to get the position of the first element if I am given its id (in this case 1). I read about the index method but don't know how to apply it to a JSON array.

Thanks in advance for the help.

Answer Source

Assuming you have your array in json variable, you might use Enumerable#detect:

json.detect { |e| e['id'] == 1 }
#⇒ {
#           "amount" => 4,
#               "id" => 1,
#        "user_name" => "Mean Dean",
#  "user_profile_id" => "1"
# }

To get an index of this element, one would use Enumerable#find_index:

json.find_index { |e| e['id'] == 1 }

To update this object, you just update the hash returned:

json.detect { |e| e['id'] == 1 }['amount'] = 500
#⇒ 500
json
#⇒ [
#  [0] {
#             "amount" => 500,  ⇐ !!!!!!!
#                 "id" => 1,
#          "user_name" => "Mean Dean",
#    "user_profile_id" => "1"
#  },
#  [1] {
#             "amount" => 7,
#                 "id" => 2,
#          "user_name" => "Mad Stan",
#    "user_profile_id" => "2"
#  },
#  [2] {
#             "amount" => 8,
#                 "id" => 3,
#          "user_name" => "Jack Dean",
#    "user_profile_id" => "3"
#  }
# ]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download