[英]JSON dumps place random digits instead of some characters in Python 3
[英]Python dumps “\n” instead of a newline in a json file
我一直在通過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化。 只需使用其中一個即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.