Python 转储“\n”而不是 json 文件中的换行符
Python dumps "\n" instead of a newline in a json file
我一直在通过 facebook 的图表 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 表示。你是 double-JSONifying 它。只需使用一个或另一个。
我一直在通过 facebook 的图表 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 表示。你是 double-JSONifying 它。只需使用一个或另一个。