我正在从API中获取数据作为python dict,并将其附加到列表中,然后将其转储到txt文件中。
我正在尝试读取txt文件中的巨大字符串并将其加载到Json对象中,但是却发现了问题。
我拿字典并使其适用于Json,即
jsonStr = json.dumps(d)
其中d是API返回的字典。
然后将此jsonStr
附加到列表中。
作为字符串,当放入txt文件时,'仍然存在../。例如
['{"md1": {"id": 422, "h": "bla"}}', '{"md2": {"id": 42211, "h": "bla2"}}']
我需要摆脱每个元素中的'
。无法找出最好的解决方法。
答案 0 :(得分:1)
您能详细说明列表的其他元素吗?如果列表中没有包含单引号的项目,则可以在文件中的文本上使用replace("'", "")
。这将全部替换为单引号。我相信,更好的方法是将JSON 添加到列表后,将其转储,如下所示:
the_list_to_which_you_append = [...]
the_list_to_which_you_append(d)
jsonStr = json.dumps(the_list_to_which_you_append)
答案 1 :(得分:0)
https://docs.python.org/3/library/json.html
要将json转换为字符串,请执行json.dumps()
要将字符串转换为json,请执行json.loads()
所以根据您的情况。在将其附加到列表之前,应先将字符串转换为json。然后将其附加到列表。然后,您可以将列表保存到文本文件。