0

How to parse the dynamic numeric keys with following json. I can able to do manually json_text['entities']['0']['uid'], how can I dynamically iterate with all keys and get all uid's

{
    "entities": {
        "0":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce96"
            },
        "1":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce97"
            },
        "2":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce98"
            }
        "3":{
            ;
            }
          :
          :
          :           
    }   
}

Code:

import os, json
import pandas as pd

path_to_json = '/home/sshuser/data/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files) 
# here I define my pandas Dataframe with the columns I want to get from the json

# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.loads(json_file.read())
        uids= json_text['entities']['0']['uid']
        print(seeMore)      

    

2 Answers 2

1

you can this

import json

with open ("yourfile.json","r") as f:
   json=json.load(f)
try:
   a=0
   while True:
      print(json["entities"][str(a)]["uid"])
      a+=1
except KeyError:
   pass
Sign up to request clarification or add additional context in comments.

Comments

1

json_text['entities'] is a dict. You can use dict.items() to iterate over key and value pairs.

for key, value in json_text['entities'].items(): # assume key 'entities' always exists
    print(f"{key} --> {value.get('uid')}") 

if key is not important, you can iterate just over .values() instead:

for value in json_text['entities'].values():
    print(value.get('uid')) 

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.