简体   繁体   English

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

[英]Python: How to convert a dictionary of lists to a JSON object?

I am new to the 'json' library thingy and having trouble converting a dictionary of lists to a JSON object, below are the dictionary I got: 我是'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)

Here was the result I got: 这是我得到的结果:

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

How to get it structured it in this way: 如何以这种方式构造它:

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

Thank you. 谢谢。

You can convert your data like this: 您可以像这样转换数据:

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'}]

Dumping this to json will result in some string like: 将其转储到json将导致一些字符串,例如:

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

If you want your json to have a guaranteed order with regard to the keys in each object, you can use: 如果您希望json在每个对象中的键方面有保证的顺序,则可以使用:

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

Restructure data first: 首先重组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)

Output: 输出:

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

A more robust solution: 一个更强大的解决方案:

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

Note that the solution above is best used in Python2, where the .keys() and .values() are ordered. 请注意,上述解决方案最适合在Python2中使用,其中.keys().values()是有序的。

You can do this if you wanted to do long version, you just have to put the two fields of data in two lists first. 如果您想做长版,则可以执行此操作,只需将数据的两个字段首先放在两个列表中即可。

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)

Output will look like: 输出将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM