【问题标题】:Python dumps "\n" instead of a newline in a json filePython 在 json 文件中转储“\n”而不是换行符
【发布时间】:2019-11-16 12:01:49
【问题描述】:

我一直在通过 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)

尽管我使用了缩进,但它并没有按照我想要的方式进行漂亮的打印。感谢您的帮助!

【问题讨论】:

  • 你不应该对对象进行两次字符串化。

标签: python json newline pretty-print


【解决方案1】:

您正在使用 json.dumps 创建数据的 JSON 表示。然后,您将使用 json.dump 创建该表示的 JSON 表示。您正在对其进行双重 JSON 化。只需使用其中一种。

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 2010-12-20
    • 2019-08-10
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多