Python - 将两个列表合并为一个json对象

时间:2016-11-28 14:05:11

标签: python json list python-3.x

我在Python中有一个执行器,它解决了两个函数,即get_tech_courses()get_music_courses()返回单个列表;分别为1和2。

列表1。

[
{'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 
{'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'}
]

列表2。

[
{'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 
{'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}
]

我想将两个列在父级courses下绑定的json数组中的列表组合在一起:

{"courses":
[{'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 

{'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'},

{'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 

{'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}]
}


这不是打印正确的json。

from concurrent.futures import ThreadPoolExecutor

import tech_course
import music_course
import json

courses = []

with ThreadPoolExecutor(max_workers=2) as executor:
    courses.append(executor.submit(tech_course.get_tech_course).result())
    courses.append(executor.submit(music_course.get_music_course).result())

print(json.dumps(courses))

1 个答案:

答案 0 :(得分:4)

尝试以下方法:

import json

list_1 = [
    {'title': 'THE COMPLETE PYTHON WEB COURSE', 'downloads': '4', 'views': '88'}, 
    {'title': 'THE COMPLETE JAVA WEB COURSE', 'downloads': '16', 'views': '156'}]

list_2 = [
    {'title': 'THE COMPLETE GUITAR COURSE', 'downloads': '18', 'views': '125'}, 
    {'title': 'THE COMPLETE KEYBOARD COURSE', 'downloads': '63', 'views': '98'}]

res_dict = {"courses": list_1 + list_2 }

to_json = json.dumps(res_dict)

<强>输出:

>>> to_json
'{"courses": [{"downloads": "4", "views": "88", "title": "THE COMPLETE PYTHON WEB COURSE"}, {"downloads": "16", "views": "156", "title": "THE COMPLETE JAVA WEB COURSE"}, {"downloads": "18", "views": "125", "title": "THE COMPLETE GUITAR COURSE"}, {"downloads": "63", "views": "98", "title": "THE COMPLETE KEYBOARD COURSE"}]}'