python - 如何将原始字符串转换为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", "\"", "}", "]"]}
如何将原始字符串转换为列表并获得我想要的结果?
解决方案
尝试使用json.loads(raw_string_list)
. 这会将 JSON-ic 字符串转换为相关的 Python 类型:)
推荐阅读
- monitoring - 在 Prometheus 中获取两个自定义时间戳之间的增量
- ios - 可以在 Codable 中使用 NSArray 吗?(将“对象映射器”转换为“可编码”)
- spring-boot - Tomcat 在部署 Spring Boot 应用程序时出错
- c++ - 函数 NetShareGetInfo 总是返回 2310(此共享不存在)
- mercurial - 恢复“hg strip”后丢失的提交
- javascript - 如何只在 div 内按下按键?
- ruby-on-rails - Aws CostExplorer Api 使用 ruby sdk 给出异常
- java - Android房间自定义更新@Query with String array crash with "sqlite syntax ? error"
- mysql - MySql 与实体框架的连接
- javascript - ForEach 不工作,但 For 工作正常