0

I am trying to get all keys from a json file in Python. How to get nested second level(x,y) and third level keys(a,b). For example, Keys: results,x,y,a,b

Code:

#open data
import json

with open('list.json') as f:
    my_dict = json.load(f)

#1
    #find keys
    for key in my_dict.keys():
         print("Keys : {}".format(key))

Json:

{
   "results":[
      {
         "x":5
      },
      {
         "x":5,
         "y":[
            1,
            2,
            3
         ]
      },
      {
         "x":5,
         "y":{
            "a":2,
            "b":67
         }
      }
   ]
}

Output:

Keys : results
NoemonGR
  • 59
  • 1
  • 9

2 Answers2

0

Use recursive function to return all nested keys. Here is the reference stackoverflow page.

import json

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is list:
            for i in value:
                if type(i) is dict:
                    yield from recursive_items(i)
        else:
            yield key

with open('list.json') as f:
    my_dict = json.load(f)

    #find keys
    for key in recursive_items(my_dict):
         print("Keys : {}".format(key))
Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13
0

You need to get the keys which are a part of the value of the JSON.

You therefore need to iterate over the values of my_dict not the keys.

pykam
  • 1,223
  • 6
  • 16
  • with value I get everything Output: (results[{'x': 5}, {'x': 5, 'y': [1, 2, 3]}, {'x': 5, 'y': {'a': 2, 'b': 67}}]) – NoemonGR Feb 06 '21 at 16:15