Python格式化JSON檔案

2021-09-23 18:19:23 字數 921 閱讀 6906

之前工作中有乙個需求是要格式化json檔案,遇到乙個問題,是要把乙個json檔案裡面的內容格式化一下,在此做個記錄

import json

class jsonformat():

"""初始化json原始檔和新檔案位址"""

def __init__(self,filepath,newpath):

self.filepath=filepath

self.newpath=newpath

def format_turn(self):

file=open(filepath,'rb')

"""轉化json資料為python物件"""

str=json.load(file)

"""把資料格式化並轉換為string"""

js_data=json.dumps(str,indent=4,separators=(',',':')).encode('utf-8').decode('raw_unicode_escape')

"""把格式化後的資料寫入新檔案"""

with open(newpath,'w') as f:

print(js_data)

f.write(js_data)

if __name__=="__main__":

filepath="c:\\users\\lenovo\\desktop\\json1.json"

newpath="c:\\users\\lenovo\\desktop\\json2.json"

obj=jsonformat(filepath,newpath)

obj.format_turn()

filepath為待格式化檔案的路徑

newpath為格式化後的檔案的路徑

Python格式化儲存json檔案

json.dumps 直接把常用引數列一下好了 引數名 解釋 obj要存入json檔案的python物件 cls預設none,則預設jsonencoder編碼,若有賦值,則是繼承此類重寫default方法,如下 class myencoder json.jsonencoder defdefault ...

Python進行JSON格式化輸出

先寫乙個字典並將其轉換成json格式 encoding utf 8 import json dic js json.dumps dic print js 列印出的是如下這個樣子,一行式的 encoding utf 8 import json dic js json.dumps dic,sort ke...

Json格式化輸出

主要目的就是格式化輸出json,這樣將輸出的字串直接寫入本地檔案作為配置檔案,閱讀起來也比較方便。另外推薦tostringbuilder,在apache的common lang3中,輸出物件時比較直觀方便。1.9.2 org.codehaus.jackson jackson core asl org...