如何在JSON数组中获取对象的索引?

时间:2017-05-23 09:00:53

标签: ruby-on-rails json ruby

我有以下格式的JSON数组,如何使用其键获取对象的位置(索引)?

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
    }
]

例如,如果我想获得第一个元素的位置,如果给出它的id(在这种情况下为1),我将如何处理它。我读到了index方法,但不知道如何将它应用于JSON数组。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

假设您的数组位于json变量中,您可以使用Enumerable#detect

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

要获取此元素的索引,可以使用Enumerable#find_index

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

要更新此对象,只需更新返回的哈希:

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"
#  }
# ]