-4

I have a JSON structure that looks like this:

json_structure = 
{
"a":1,
"b":2,
"c":[
     {
     "d":4,
     "e":5,
     "f":{
         "g":6
         }
     }
    ]
"d":[
     {
      "h": 7,
      "i": 8,
      }
    ]
}

I am able to get a, b, c, d no problem using:

json_structure.keys()

But now I want to get only the c nested keys (d, e, f).

Haven't found a way to do this when explicitly stating c keys only.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
getunstuck
  • 49
  • 4
  • Similar question https://stackoverflow.com/questions/3860813/recursively-traverse-multidimensional-dictionary-dimension-unknown – Albin Paul Feb 12 '23 at 01:00
  • 2
    Just use the key and take the first element of the list? `json_structure['c'][0].keys()`? – Mark Feb 12 '23 at 01:08

1 Answers1

1

You could write a few utility functions that recursively drill down the structure to access any specific value, keys or items. This could process lists as if they were dictionaries with the keys being the indices.

def deepValue(D,key,*rest,default=None):
    try:    return deepValue(D[key],*rest,default=default) if rest else D[key]
    except: return default

def deepKeys(D,key,*rest):
    try:
        return deepKeys(D[key],*rest) if rest \
          else D[key].keys() if isinstance(D[key],dict) \
          else range(len(D[key]))
    except:
        return []

def deepItems(D,key,*rest):
    try:
        if rest:
            yield from deepItems(D[key],*rest)
        elif isinstance(D[key],dict):
            yield from D[key].items()
        else:
            yield from enumerate(D[key])
    except: return

output:

for k in deepKeys(json_structure,"c",0):
    print(k)

# d
# e
# f


print(deepValue(json_structure,"c",0))

# {'d': 4, 'e': 5, 'f': {'g': 6}}

print(deepValue(json_structure,"c",0,"d"))

# 4    
    

for k,v in deepItems(json_structure,"c",0):
    print(k,v)

# d 4
# e 5
# f {'g': 6}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • This is an cool approach and seemed to work. Only works with lists though. What if I had a dictionary nested in there. For instance: {"a": 1, "b": 2, "c": { "d": 3, "e": 5, "f": {"g": 6, "h": 7} } } – getunstuck Feb 12 '23 at 23:43
  • It is designed to work with any combination of nested dictionaries and lists – Alain T. Feb 13 '23 at 00:02