我一直在通过 facebook 的 Graph API 获取一些数据,并将其以 json 格式保存在一个新文件中。但是,每当我尝试将其保存在文件中时,新行实际上并不显示为换行符,而是显示为“\n”。此外,在任何数据之前还会附加一个反斜杠。
例如,
我希望数据以这种格式保存:
{
"feed": {
"data": [
{
"message": "XYZ",
"created_time": "0000-00-0000:00:00+0000",
"id": ABC"
}
但它是以这种格式保存的(在一行中)
"{\n\"feed\": {\n\"data\": [\n{\n\"message\": \"XYZ\",\n\"created_time\": \"0000-00-0000:00:00+0000\",\n\"id\": \"ABC\"\n}
如何将其保存为第一种格式而不是第二种格式?
我一直在使用这段代码:
url2 = '{0}?fields={1}&access_token={2}'.format(url,fields,token) #the format in which the API receives the request to get the data which is needed
# token is the access token, url is to connect to fb and fields is the data I want
size = os.path.getsize('new.json') #gets the size of the file
content = requests.get(url2).json() #obtaining the content
obj = json.dumps(content,indent = 4)
with open('new.json','r+') as f: #if file size is 0, delete all content and rewrite with new and old content
if size>0:
f.truncate(0)
json.dump(obj,f)
尽管我使用了缩进,但它并没有按照我想要的方式漂亮地打印。感谢帮助!
最佳答案
您正在使用 json.dumps
创建数据的 JSON 表示形式。然后,您使用 json.dump 创建该表示形式的 JSON 表示形式。你正在双重 JSON化它。只需使用其中之一即可。
关于Python 转储 "\n"而不是 json 文件中的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56910059/