Python:如何将列表字典转换为JSON对象?

时间:2017-11-18 15:43:00

标签: python json list dictionary

我是'json'库的新手,无法将列表字典转换为JSON对象,下面是我得到的字典:

import json

data = {

     'title' : ['Seven days', 'Not Today', 'Bad Moms'],
     'date'  : ['July 17', 'Aug 18', 'Jan 19']

}

json_data = json.dumps(data)

print(json_data)

这是我得到的结果:

{"title" : ['Seven days', 'Not Today', 'Bad Moms'], "date" : ['July 17', 'Aug 18', 'Jan 19']}

如何以这种方式构建它:

{"title" : "Seven days","date" : "July 17"}, {"title" : "Not Today","date" : "Aug 18"}, {"title" : "Bad Mom","date" : "Jan 19"}

谢谢。

3 个答案:

答案 0 :(得分:2)

您可以像这样转换数据:

d = [{'title': t, 'date': d} for t, d in zip(data['title'], data['date'])]
#[{'title': 'Seven days', 'date': 'July 17'}, 
# {'title': 'Not Today', 'date': 'Aug 18'}, 
# {'title': 'Bad Moms', 'date': 'Jan 19'}]

将其转储到json会产生一些字符串,如:

'[{"title": "Seven days", "date": "July 17"}, {"title": "Not Today", "date": "Aug 18"}, {"title": "Bad Moms", "date": "Jan 19"}]'

如果您希望您的json有关于每个对象中的键的保证顺序,您可以使用:

from collections import OrderedDict
d = [OrderedDict([('title', t), ('date', d)]) for t, d in zip(data['title'], data['date'])]

答案 1 :(得分:1)

首先重组data

import json
data = {

 'title' : ['Seven days', 'Not Today', 'Bad Moms'],
 'date'  : ['July 17', 'Aug 18', 'Jan 19']

}
new_data = [{"title":i, "date":b} for i, b in zip(data["title"], data["date"])]
final_data = json.dumps(new_data)

输出:

'[{"date": "July 17", "title": "Seven days"}, {"date": "Aug 18", "title": "Not Today"}, {"date": "Jan 19", "title": "Bad Moms"}]'

更强大的解决方案:

new_data = [dict(zip(data.keys(), i)) for i in zip(*data.values())]

请注意,上述解决方案最适用于Python2,其中.keys().values()是有序的。

答案 2 :(得分:1)

如果你想做长版本,你可以这样做,你只需要先将两个数据字段放在两个列表中。

import json

data = {

     'title' : ['Seven days', 'Not Today', 'Bad Moms'],
     'date'  : ['July 17', 'Aug 18', 'Jan 19']

}

titles = data['title']
dates = data['date']

lst = list()

for i in range(len(titles)):
    a = dict()
    a["title"] = titles[i]
    a["date"] = dates[i]
    lst.append(a)

print json.dumps(lst)

输出如下:

[{"date": "July 17", "title": "Seven days"}, {"date": "Aug 18", "title": "Not Today"}, {"date": "Jan 19", "title": "Bad Moms"}]