将嵌套的json转换为没有嵌套对象的字典格式 [英] Convert the nested json into a dictionary format with no nested objects
问题描述
我具有以下格式的输入数据:
I have the input data in below format:
data = [[u'Richard', u'48', [u'Josh', u'Beth'], {u'city': u'Seattle', u'Disability': u'no', u'enterprenuer': u'yes'}], [u'Bryan', u'32',[], {u'city': u'NY', u'enterprenuer': u'no', u'wfh': u'yes', u'disability': u'no', u'Visa': u'no'}]]
稍后执行json.dumps
的内容将变为:
Which later on doing json.dumps
becomes:
[["Richard", "48", ["Josh", "Beth"], {"city": "Seattle", "enterprenuer": "yes", "Disability": "no"}], ["Bryan", "32", [], {"Visa": "no", "city": "NY", "wfh": "yes", "enterprenuer": "no", "disability": "no"}]]
此外,我还有另一个列表,其中包含该字典的键:
Also, I have another list which holds the keys for the dict:
key_list = ["Name", "Age", "Children", "details"]
我尝试了以下代码:
list_of_dicts = []
for d in data:
dict = {}
for i in range(0, len(key_list)-1):
dict[key_list[i]] = d[i]
list_of_dicts.append(dict)
有了这个,我就能得到new_dict
:
With this I was able to get new_dict
:
[{'Age': u'48', 'Name': u'Richard', 'Children': [u'Josh', u'Beth']}, {'Age': u'32', 'Name': u'Bryan', 'Children': []}]
但是我无法将嵌套的dict从data
放入new_dict
中,而无需再次在其上运行代码.我不想多次运行操作.
另外,我也在考虑是否还有更好的方法来删除嵌套列表,但是在多次尝试之后,我一直跟踪并弄乱了我的代码.
But I am not able to get the nested dict from data
into the new_dict
without the need to run code on it again. I don't want to run operation multiple times.
Also, I was thinking if there's any better way to remove the nested list as well but after multiple hit and trial I got side tracked and messed up my code.
这是预期的输出:
[{"Name":"Richard","Age":"48","Children":"Josh,Beth","city":"Seattle","enterprenuer":"yes","Disability":"no"},{"Name":"Bryan","Age":"32","Children":"","Visa":"no","city":"NY","wfh":"yes","enterprenuer":"no","disability":"no"}]
推荐答案
您可以尝试:
1)在python3中:
1) in python3:
from pprint import pprint
data = [["Richard", "48", ["Josh", "Beth"], {"city": "Seattle", "enterprenuer": "yes", "Disability": "no"}], ["Bryan", "32", [], {"Visa": "no", "city": "NY", "wfh": "yes", "enterprenuer": "no", "disability": "no"}]]
key_list = ["Name", "Age", "Children", "details"]
pprint([dict(zip(key_list[:2], e[:2]), **{key_list[2]: ','.join(e[2])}, **e[3]) for e in data])
输出:
[{'Name': 'Richard',
'Age': '48',
'Children': 'Josh,Beth',
'city': 'Seattle',
'Disability': 'no',
'enterprenuer': 'yes'},
{'Name': 'Bryan',
'Age': '32',
'Children': '',
'city': 'NY',
'enterprenuer': 'no',
'wfh': 'yes',
'disability': 'no',
'Visa': 'no'}]
2)在python2中:
2) in python2:
pprint([dict(zip(key_list[:2], e[:2]), **dict([(key_list[2], ','.join(e[2]))], **e[3])) for e in data])
输出:
[{'Age': '48',
'Children': 'Josh,Beth',
'Disability': 'no',
'Name': 'Richard',
'city': 'Seattle',
'enterprenuer': 'yes'},
{'Age': '32',
'Children': '',
'Name': 'Bryan',
'Visa': 'no',
'city': 'NY',
'disability': 'no',
'enterprenuer': 'no',
'wfh': 'yes'}]
这篇关于将嵌套的json转换为没有嵌套对象的字典格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!