目标:将字符串列表转换为字典列表
我有以下字符串列表
info = ['{"contributors": null, "truncated": true, "text": "hey there"}',
'{"contributors": null, "truncated": false, "text": "how are you"}',
'{"contributors": 10, "truncated": false, "text": "howdy"}']
Run Code Online (Sandbox Code Playgroud)
期望的输出:
desired_info = [{"contributors": null, "truncated": true, "text": "hey there"},
{"contributors": null, "truncated": false, "text": "how are you"},
{"contributors": 10, "truncated": false, "text": "howdy"}]
Run Code Online (Sandbox Code Playgroud)
问题:如何将字符串列表转换为字典列表?
你可以使用json.loads:
import json
info = ['{"contributors": null, "truncated": true, "text": "hey there"}',
'{"contributors": null, "truncated": false, "text": "how are you"}',
'{"contributors": 10, "truncated": false, "text": "howdy"}']
info = [json.loads(x) for x in info]
print(info)
Run Code Online (Sandbox Code Playgroud)
输出:
[{'contributors': None, 'truncated': True, 'text': 'hey there'}, {'contributors': None, 'truncated': False, 'text': 'how are you'}, {'contributors': 10, 'truncated': False, 'text': 'howdy'}]
Run Code Online (Sandbox Code Playgroud)