2

I have a dictionary object in python, I will give two parameters to a method which is some key name key and the json object, i want to receive an output that will have the absolute path of the key.

Example json object and the key name is "year"

{
  "name": "John",
  "age": 30,
  "cars": {
    "car1": {
      "name": "CD300",
      "make": {
        "company": "Benz",
        "year": "2019"
      }
    }
  }
}

my function will be something like below

def get_abs_path(json, key):
    print(res)

expected output res = cars.car1.make.company

3
  • you want abs path of the key ? Commented Apr 29, 2019 at 7:51
  • in that case get_abs_path(json, 'year') will return cars.car1.make.year right ? @Ashwin S Commented Apr 29, 2019 at 7:51
  • @AsifMohammed yes Commented Apr 29, 2019 at 7:53

1 Answer 1

5
def is_valid(json, key):
    if not isinstance(json, dict):
        return None
    if key in json.keys():
        return key
    ans = None
    for json_key in json.keys():
        r = is_valid(json[json_key], key)
        if r is None:
            continue
        else :
            ans = "{}.{}".format(json_key, r)
    return ans

a = {
    "name": "John",
    "age": 30,
    "cars": {
        "car1": {
            "name": "CD300",
            "make": {
                "company": "Benz",
                "year": "2019"
            }
        }
    }
}
def get_abs_path(json, key):
    path = is_valid(json, key)
    print(path)

get_abs_path(a, 'company')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.