简体   繁体   中英

Converting a JSON strings list to a JSON array in Python

Having this list with two JSON strings on it:

myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']

How can I convert this to a JSON array? This is my desired output:

[{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}, 
{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}]

I know I can do a dirty solution by just doing myJSONStringList.replace("'", "") , but is there any pythonic solution to this by using, for example, the json module?

Thanks in advance

decode JSON strings into dicts and put them in a list, last, convert the list to JSON

json_list = []
json_list.append(json.loads(JSON_STRING))
json.dumps(json_list)

or more pythonic syntax

output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])

Use json.dumps before json.loads to convert your data to dictionary object This also helps prevent valueError: Expecting property name enclosed in double quotes .

Ex:

import json
myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']

print([json.loads(json.dumps(i)) for i in myJSONStringList])

Output:

[u'{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}', u'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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