CodeWalker CodeWalker - 5 days ago 5
JSON Question

Python - Combine two lists into one json object

I have an executor in Python which addresses 2 functions namely

get_tech_courses()
and
get_music_courses()
returning individual lists; 1 and 2 respectively.

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


I want to combine both the lists in a json array tied under the parent courses like this :

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




This is not printing proper 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))

Answer

Try the following:

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)

Output:

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