I
I
Ismail2020-02-19 13:49:18
ruby
Ismail, 2020-02-19 13:49:18

How can a nested hash be obtained from the value in that hash?

I want to get the entire hash only by value from a JSON file. Example:

JSON

{
    "company": {
        "employee": {
            "first_employee": {
                "id": 1,
                "position": "farmer",
                "age": 25,
                "name": "Michael"
            },
            "second_employee": {
                "id": 2,
                "position": "builder",
                "age": 29,
                "name": "Steve"
            }
        }
    }
}


The code:
ruby

require "json"
file = File.read("example.json")
data_hash = JSON.parse(file)
#Далее пример (Псевдокод):
p data_hash["position" = "farmer"]
#Должно выдать:
"first_employee": {
    "id": 1,
    "position": "farmer",
    "age": 25,
    "name": "Michael"
}



That is, make a cycle that looks for a value in this JSON, finds the hash in which it is located and issues it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-02-19
@gosugod

data_hash["company"]["employee"].select{|k, v| v["position"] == "farmer"}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question