How to explicitly set carriage return when executing json.dump?

My python script creates a json file. And I have to support this python file running on windows and linux. The problem is the rollback carriage return on windows and linux. When I run this code in windows, it outputs CRLF json. And it outputs LF json when I run this on linux.

So, how to explicitly set carriage return when doing json dump in python3.5? i couln

import json
fpath = "hoge.json"
data = {"AGE": 12, "HOGE": [{"GUA": 3}]}
with open(fpath, 'wt', encoding="utf-8") as outfile:
    json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=False)

http://docs.python.jp/3/library/json.html

+3
source share
2 answers

CRLF ( JSON , , , , CRLF), open, json.

newline='\r\n' open, \n, json \r\n, , os.linesep ( \r\n Windows \n ):

with open(fpath, 'w', encoding="utf-8", newline='\r\n') as outfile:
    json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=False)
+4

- json (https://tools.ietf.org/html/rfc7159 2 ):

.

  ws = *(
          %x20 /              ; Space
          %x09 /              ; Horizontal tab
          %x0A /              ; Line feed or New line
          %x0D )              ; Carriage return

, CR, LF .

+2

Source: https://habr.com/ru/post/1534802/


All Articles