Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python - How to save a tabbed json file

I have a function:

def save(path,data):
    file = open(path,'w',encoding='utf-8')
    file.write(json.dumps(data))
    file.close()

It saves the file, but without tabbing. Everything goes in one line.

save('1.json',{"1":"222"})

How do I make it save in tab format?

{
  "1":"222"
}
question from:https://stackoverflow.com/questions/65914704/how-to-save-a-tabbed-json-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use indent argument with json.dumps as below:

import json

def save(path, data):    
    file = open(path,'w',encoding='utf-8')
    file.write(json.dumps(data, indent=4))
    file.close()
    
save('1.json',{"1":"222"})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...