I want to use ruby for hash like xpath.

Asked 2 years ago, Updated 2 years ago, 31 views

When there was a nesting structure of hash in ruby (like the value of hash has hash again), I wanted to specify elements in xml as xpath.For example, if you want to delete an element,

h={name:
  {"Japanese_first_name"=>"Taro",
   "Japanese_last_name" = > "Tanaka",
   "English_first" = > "Taro",
   "English_last" = > "Tanaka"
  },
  age —18
}

del(h, [:name, /Japanese /])
# =>{:name=>{"english_first"=>"Taro", "english_last"=>"Tanaka"},:age=>18}

It would be nice to have a method like , where del represents the path of hash to compare with case (or rather ===).

When I tried implementing this del, it looked like this.

def del(h,xpath_ish)
  return h.reject { | k , v | xpath_ish.first === k } if xpath_ish.size == 1
  h.map do|k,v|
    new_v=xpath_ish.first===k?del(v,xpath_ish.drop(1)):v
    [k, new_v]
  end.to_h
end

Now that you've written and defined del, you'd like to define map, redundancy, etc. as well.

However, I thought that if you use ruby, you might want to do it relatively well, so I thought that some existing libraries would do this.

Question

    Is there a library where
  • ruby can perform operations while specifying elements in terms of xpath for hash?
    • Especially if you read json with hash.
  • Especially if you read json with hash.

ruby

2022-09-29 20:26

1 Answers

There is a gem called jsonpath.


2022-09-29 20:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.