简体   繁体   English

在Python中将JSON字符串列表转换为JSON数组

[英]Converting a JSON strings list to a JSON array in Python

Having this list with two JSON strings on it: 将此列表包含两个JSON strings

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? 如何将其转换为JSON数组? 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? 我知道我可以通过执行myJSONStringList.replace("'", "")来做一个肮脏的解决方案,但是通过使用例如json模块,是否有任何pythonic解决方案?

Thanks in advance 提前致谢

decode JSON strings into dicts and put them in a list, last, convert the list to JSON 将JSON字符串解码为dicts并将它们放入列表中,最后将列表转换为JSON

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

or more pythonic syntax 或更多pythonic语法

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 . 使用json.dumps之前json.loads将数据转换成字典对象这也有助于防止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"}']

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

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