此列表中包含两个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"}']
如何将其转换为JSON数组?这是我想要的输出:
[{"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"}]
我知道我可以通过执行myJSONStringList.replace("'", "")
来做一个肮脏的解决方案,但是通过使用json
模块,有没有任何pythonic解决方案?
提前致谢
答案 0 :(得分:2)
将JSON字符串解码为dicts并将它们放入列表中,最后将列表转换为JSON
json_list = []
json_list.append(json.loads(JSON_STRING))
json.dumps(json_list)
或更多pythonic语法
output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])
答案 1 :(得分:1)
在json.dumps
之前使用json.loads
将您的数据转换为字典对象这也有助于阻止valueError: Expecting property name enclosed in double quotes
。
<强>实施例强>
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])
<强>输出:强>
[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"}']