Home > Enterprise >  Python: Find a JSON value and return it's sub-objects too
Python: Find a JSON value and return it's sub-objects too

Time:09-27

I'm messing around with JSON, and Python.

I'm trying to format a full pretty-print of the 1st-level objects (in this case example1 and example2.) and their sub-objects (2nd and 3rd level). How would I retrieve 2nd-level data stored under echo, and further down the line, how would I retrieve 3rd level data stored under juliett? I know how to perform the necessary printing and format operations but the data retrieval is hard.

I haven't tried to write any code to do this as I am quite new to Python (having started experimenting last week). Help would be appreciated.

Example:

{
    "example1": {
        "alpha": "bravo",
        "charlie": "delta",
        "echo":
            {
                "foxtrot": "golf",
                "hotel": "india",
                "juliett": {
                    "kilo": "lima",
                    "mike": "november"
                }
            }
    },
    "example2": {
        "alpha": "bravo",
        "charlie": "delta",
        "echo":
            {
                "foxtrot": "golf",
                "hotel": "india",
                "juliett": {
                    "kilo": "lima",
                    "mike": "november"
                }
            }
    }
}

CodePudding user response:

IIUC, you want the json module:

import json

my_dict = json.loads(open("data.json").read())

>>> my_dict["example1"]["echo"]
{'foxtrot': 'golf',
 'hotel': 'india',
 'juliett': {'kilo': 'lima', 'mike': 'november'}}

>>> my_dict["example1"]["echo"]["juliett"]
{'kilo': 'lima', 'mike': 'november'}
data.json:
{
  "example1": {
    "alpha": "bravo",
    "charlie": "delta",
    "echo": {
      "foxtrot": "golf",
      "hotel": "india",
      "juliett": {
        "kilo": "lima",
        "mike": "november"
      }
    }
  },
  "example2": {
    "alpha": "bravo",
    "charlie": "delta",
    "echo": {
      "foxtrot": "golf",
      "hotel": "india",
      "juliett": {
        "kilo": "lima",
        "mike": "november"
      }
    }
  }
}
  • Related