I have a dynamic json, in whcih key(attributes) will be different based on records.
I want to write below json data into csv file:
[{"Id": "12345",
"attributes": {"Address": [{"label": "United Kingdom",
"value": {"AddressLine": [{"value": "Baker "
"Street"}]}},
{"label": "United States",
"value": {"AddressLine": [{"value": "Florida"}]}}],
"CountryCode": [{"value": "Australia"}],
"Identifiers": [{"value": {"Type": [{"value": "Licence Id"}]}},
{"value": {"Type": [{"value": "NPI"}]}}],
"StatusReasonCode": [{"value": "XXX"}],
"UniqueId": [{"value": "71581742"}]},
"createdBy": "Rahul"}]
Data is expected in below format of the csv:
ID, createdBy, CountryCode, StatusReasonCode, Identifiers, UniqueId, AddressLine
12345,Rahul,Australia,XXX,Licence Id,71581742,Baker Street
12345,Rahul,Australia,XXX,NPI,71581742,Florida
Here is my code to extract the data from json:
import json
with open('data.json') as f:
data = json.load(f)
for key,value in data.items():
if(type(value))==str:
print(key + ',' + value)
# global res
res =[]
if(type(value))==list:
for fg in value:
crosswalk_final=fg['value']
if (type(value))== dict:
for key1,val in value.items():
for k in val:
if type(k['value']) == dict:
for sub_key,sub_value in k.items():
if(type(sub_value)) == dict:
for child_key,child_value in sub_value.items():
if(type(child_value)) == list:
for m in child_value:
if type(m['value']) == dict:
for qaq,waq in m.items():
if (isinstance(waq, dict)):
for our,pur in waq.items():
for qq in pur:
print(our+','+qq['value'])
else:
pass
print(key1+'_'+sub_key+'_'+child_key+','+m['value'])
else:
attr1=(key+'_'+key1+','+k['value'])
print((attr1))
The above code is giving me result in below format:
Id,12345
createdBy,Rahul
attributes_UniqueId,71581742
attributes_CountryCode,Australia
attributes_StatusReasonCode,XXX
Address_value_AddressLine,Baker Street
Address_value_AddressLine,Florida
Identifiers_value_Type,Licence Id
Identifiers_value_Type,NPI
However I am not sure how to write it in my csv (in the same format shown above).