首页 > 解决方案 > 如何将原始字符串转换为python3中的列表?

问题描述

我想将原始字符串转换为 python3.6 中的列表

import json
from collections import OrderedDict

raw_string_list = "[{\"number\":1,\"url\":\"https:\\/\\/www.google.com\",\"content\":\"I\'am a a\"},{\"number\":2,\"url\":\"https:\\/\\/www.stackoverflow.com\",\"content\":\"I\'am a b\"}]"
json_dict = OrderedDict()
json_dict["content"] = list(raw_string_list)

with open("test.json", 'w', encoding="utf-8") as makefile:
    json.dump(json_dict, makefile, ensure_ascii=False)
makefile.close()

我想要的json文件在下面。

{"content":[{"number":1,"url":"https://www.google.com","content":"'I'am a a"},{"number":2,"url":"https://www.stackoverflow.com","content":"'I'am a b"}]}

但实际结果如下。

{"content": ["[", "{", "\"", "n", "u", "m", "b", "e", "r", "\"", ":", "1", ",", "\"", "u", "r", "l", "\"", ":", "\"", "h", "t", "t", "p", "s", ":", "\\", "/", "\\", "/", "w", "w", "w", ".", "g", "o", "o", "g", "l", "e", ".", "c", "o", "m", "\"", ",", "\"", "c", "o", "n", "t", "e", "n", "t", "\"", ":", "\"", "I", "'", "a", "m", " ", "a", " ", "a", "\"", "}", ",", "{", "\"", "n", "u", "m", "b", "e", "r", "\"", ":", "2", ",", "\"", "u", "r", "l", "\"", ":", "\"", "h", "t", "t", "p", "s", ":", "\\", "/", "\\", "/", "w", "w", "w", ".", "s", "t", "a", "c", "k", "o", "v", "e", "r", "f", "l", "o", "w", ".", "c", "o", "m", "\"", ",", "\"", "c", "o", "n", "t", "e", "n", "t", "\"", ":", "\"", "I", "'", "a", "m", " ", "a", " ", "b", "\"", "}", "]"]}

如何将原始字符串转换为列表并获得我想要的结果?

标签: pythonpython-3.x

解决方案


尝试使用json.loads(raw_string_list). 这会将 JSON-ic 字符串转换为相关的 Python 类型:)


推荐阅读