簡體   English   中英

如何使用 Python 打印 JSON 屬性的換行符?

[英]How to print the line breaks of a JSON attribute using Python?

我有以下情況:

  • 我有以下 JSON 文件:

     { "name":"whatever", "lyric":"here comes the music another line whatever... bla bla bla final" }
  • 下一步是加載 JSON 文件並將屬性"name"更改為"songs real name"

  • 最后一步是將 JSON 寫入輸出文件,保持相同的輸入格式(使 JSON 讀取更容易),但它確實將換行符打印為轉義字符,如下所示:

     { "name":"songs real name", "lyric":"here comes the music \\n another line \\n whatever... \\n bla bla bla \\n final" }

期望的輸出:

{
   "name":"songs real name",
   "lyric":"here comes the music
      another line
      whatever...
      bla bla bla
      final"
}

這是python代碼:

with open(file, "r") as data_file:    
    json_data=data_file.read()
data_file.close()
json_data["name"]="song's real name"

with open(outputfile)
    jsonFile.write(json.dumps(data,indent=4, sort_keys=True)

一切正常,只是它沒有打印斷行。

我得到了答案,基本上我所做的是替換 json.dumps:

with open(file, "r") as data_file:    
json_data=data_file.read()
data_file.close()
json_data["name"]="song's real name"

with open(outputfile)
    jsonFile.write(json.dumps(data,indent=4, sort_keys=True, separators=(',', ': ')).replace('\\n','\n'))

之后,我得到了我想要的輸出文件:

{
"name" : "歌曲真實姓名",
“歌詞”:“音樂來了
另一行
任何...
布拉布拉布拉
最終的”
}

謝謝你們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM