Reputation: 844
I am trying to convert JSON files to CSV using below code. The PARENT_ID and PARENT_TYPE fields can be NULL most of the times. If I use result["parent"]["id"] it returns KeyError. That's why I thought of using get() to return whatever value they hold. But I am getting TypeError('list indices must be integers, not str',) for these fields. Can anyone suggest any workaround? Thanks in advance!
"parent" is a list within "result" dict.
my_dict_list =[]
try:
for f in os.listdir(file_dir):
if f.endswith('.json') and f.startswith('folders_'):
file_path = os.path.join(file_dir, f)
data = open(file_path, 'r')
for line in data:
my_dict = {}
parsed_data = json.loads(line)
my_dict["REQUEST_ID"] = parsed_data["requestId"]
my_dict["SUCCESS"] = parsed_data["success"]
for result in parsed_data["result"]:
my_dict["NAME"] = result["name"]
my_dict["DESCRIPTION"] = result["description"]
my_dict["FOLDER_ID"] = result["folderId"]["id"]
my_dict["FOLDER_ID_TYPE"] = result["folderId"]["type"]
my_dict["FOLDER_TYPE"] = result["folderType"]
my_dict["PARENT_ID"] = result.get(["parent"]["id"])
my_dict["PARENT_TYPE"] = result.get(["parent"]["type"])
Upvotes: 0
Views: 61
Reputation: 5011
Currently you are trying to access the member "id" from a list with the string "parent" in the following line:
my_dict["PARENT_ID"] = result.get(["parent"]["id"])
You have to check if the result dict contains the key "parent". The get method of your result dict can be used for this.
It returns None if the dict does not contain the key "parent". Otherwise use the get method and try to get the id of the parent
Your code has to be
my_dict["PARENT_ID"] = result["parent"].get("id") if result.get("parent") else None
Upvotes: 1