'Nested Json to csv using python (recursion)
I know this question has been asked many times. But I am stuck at one point and not got any proper solution that is why I want some help.
So I have nested JSON structure . I have flatten it using below code which I found here
def flatten_json(y):
out = {}
def flatten(x, name=''):
if type(x) is dict:
for a in x:
flatten(x[a], name + a + '.')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '.')
i += 1
else:
out[name[:-1]] = x
flatten(y)
return out
Everything is perfect but when there is structure like dictionary inside list [{},{}] without key to dictionary. It assigns index to it and I don't want it.
Current Output:
0._id.$oid 0.libId 0.personalinfo.name 0.personalinfo.marks.maths.0 0.personalinfo.marks.physic.1 0.clginfo.certificates.0.cert_name_1 0.clginfo.certificates.0.cert_no_1 0.clginfo.certificates.0.cert_exp_1 0.clginfo.certificates.1.cert_name_2 0.clginfo.certificates.1.cert_no_2 0.clginfo.certificates.0.cert_exp_2
Expected Output:
_id.$oid libId personalinfo.name personalinfo.marks.maths.0 personalinfo.marks.physic.1 clginfo.certificates.cert_name_1.0 clginfo.certificates.cert_no_1.0 clginfo.certificates.cert_exp_1.0 clginfo.certificates.cert_name_2.1 clginfo.certificates.cert_no_2.1 clginfo.certificates.cert_exp_2.1
I am very bad at recursion. So please help with some code it will be more helpful. Thank you in advance!
Input:
[{
"id":
{
"$oid": "00001"
},
"libId":11111,
"personalinfo":
{
"Name":"xyz",
"marks":
[
"maths":80,
"physic":90
.....
]
},
"clginfo"
{
"certificates":
[
{
"cert_name_1":"xxx",
"cert_no_1":12345,
"cert_exp.1":"20/2/20202"
},
{
"cert_name_2":"xxx",
"cert_no_2":12345,
"cert_exp_2":"20/2/20202"
},
......//could be up to 10
]
}}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
