參數(shù)名 | 解釋 |
---|---|
obj | 要存入json文件的python對(duì)象 |
fp | 文件句柄 |
ensure_ascii | 設(shè)置為False的話才可以把中文以中文的形式存到文件里,否則會(huì)是'\xXX\xXX'這種 |
indent | 縮進(jìn)的空格數(shù),設(shè)置為非零值時(shí),就起到了格式化的效果,比較美觀 |
也就是說(shuō)在使用json.dump()的時(shí)候設(shè)置一下indent參數(shù)的值就好了。比如json.dump(json_dict, f, indent=4),加與不加的區(qū)別如下:
{"title_pinyin":"gywxw","title":"隔云勿相望","url":"http://www.ty2016.net/book/gywxw/","description":"大學(xué)剛畢業(yè),她嫁給了林安森可是結(jié)婚三年,電視上??吹剿鱿鞣N場(chǎng)合攜女相伴,她卻再?zèng)]再親眼見(jiàn)過(guò)他。"}
{ "title_pinyin":"gywxw", "title":"隔云勿相望", "url":"http://www.ty2016.net/book/gywxw/", "description":"大學(xué)剛畢業(yè),她嫁給了林安森可是結(jié)婚三年,電視上??吹剿鱿鞣N場(chǎng)合攜女相伴,她卻再?zèng)]再親眼見(jiàn)過(guò)他。" }
直接粘過(guò)來(lái)了,不難理解,效果跟上邊是一樣的。
# -*- encoding: utf-8 -*- class JsonFormatter: def __init__(self, intend=4, name="", encoding="utf-8"): ''' intend: 縮進(jìn)空格數(shù) name: 文件名 encoding: 文件編碼 ''' self.name = name self.intend = intend self.encoding = encoding self.stack = [] self.obj = None self.source = self.get_source(name, self.encoding) self.prepare() @staticmethod def json_str(s): ''' 給字符串套上雙引號(hào) ''' return '"' + s + '"' @staticmethod def get_source(name, encoding="utf-8"): with open(name, 'r', encoding=encoding) as f: # 當(dāng)不給split函數(shù)傳遞任何參數(shù)時(shí),分隔符sep會(huì)采用任意形式的空白字符:空格、tab、換行、回車(chē)以及換頁(yè)符 return ''.join(f.read().split()) def prepare(self): try: # python對(duì)象和json格式還是略有不同 self.source = self.source.replace("null", "None").replace("true", "True").replace("false", "False") self.obj = eval(self.source) except: # json string 一定滿足python dict和list的組合 raise Exception('Invalid json string!') def line_intend(self, level=0): return '\n' + ' ' * self.intend * level def parse_dict(self,obj=None,intend_level=0): if intend_level == 0: # 這個(gè)判斷是為了防止文件開(kāi)頭出現(xiàn)空行 self.stack.append('{') else: self.stack.append(self.line_intend(intend_level)+'{') intend_level += 1 i = 0 for key, value in obj.items(): key = self.json_str(str(key)) self.stack.append(self.line_intend(intend_level)+key+':') self.parse(value, intend_level) if i != len(obj.items())-1: # 這個(gè)處理是為了防止最后一對(duì)kv后面還有個(gè)逗號(hào),這樣會(huì)造成json.load()函數(shù)無(wú)法讀取 self.stack.append(',') i += 1 self.stack.append(self.line_intend(intend_level-1)+'}') def parse_list(self, obj=None, intend_level=0): if intend_level == 0: self.stack.append('[') else: self.stack.append(self.line_intend(intend_level)+'[') intend_level += 1 for i, item in zip(range(0, len(obj)), obj): self.parse(item, intend_level) if i != len(obj)-1: self.stack.append(',') self.stack.append(self.line_intend(intend_level-1)+']') def parse(self, obj, intend_level=0): if obj is None: self.stack.append('null') elif obj is True: self.stack.append('true') elif obj is False: self.stack.append('false') elif isinstance(obj, (int, float)): self.stack.append(str(obj)) elif isinstance(obj, str): self.stack.append(self.json_str(obj)) elif isinstance(obj, (list, tuple)): self.parse_list(obj, intend_level) elif isinstance(obj, dict): self.parse_dict(obj, intend_level) else: raise Exception('Invalid json type %s!' % obj) def render(self): self.parse(self.obj, 0) res_file = self.name res = ''.join(self.stack) with open(res_file, 'w', encoding=self.encoding) as f: f.write(res) if __name__ == "__main__": jf = JsonFormatter(name="json.txt") jf.render()
以后碰見(jiàn)問(wèn)題不能這樣焦躁了,先靜下心來(lái)看看API吧,說(shuō)不定答案就在里面。
補(bǔ)充:python如何將數(shù)據(jù)保存到本地json文件
之前做了dict字典的合并,這一篇會(huì)將dict數(shù)據(jù)轉(zhuǎn)換成json格式的數(shù)據(jù)保存在本地,并在需要的時(shí)候讀取顯示。
@app.route('/', methods=['GET', 'POST']) def detail(): one = {'name': 'xiaozhi', 'age': 188} mess1 = ['sss is sss', 'aaa aa aaaa'] two = {"mess1": mess1} data = dict(one, **two) jsonData = json.dumps(data) fileObject = open('data.json', 'w') fileObject.write(jsonData) fileObject.close() return jsonify({"success": 200, "data": data})
在瀏覽器輸入U(xiǎn)RL后,json文件在本地創(chuàng)建,打開(kāi)我們可以看到數(shù)據(jù)已經(jīng)成功保存:
如圖,我們做一個(gè)點(diǎn)擊事件,點(diǎn)擊按鈕讀取.json文件,并將信息顯示到對(duì)應(yīng)的位置上
@app.route('/history', methods=['GET', 'POST']) def history(): data = json.loads(request.form.get('data')) number = data['number'] print(number) if number == '01': file = 'data.json' fb = open(file, 'r') dicts = json.load(fb) fb.close() myjson = json.dumps(dicts) return myjson return 'no history'
!DOCTYPE html> html lang="en"> head> meta charset="UTF-8"> title>test/title> script src="{{ url_for('static', filename='js/jquery-1.7.1.min.js') }}">/script> /head> body> input type="button" value="show log" οnclick="show()"/> input type="hidden" id="number" value="01">br> 用戶(hù):a id="user">/a>br> 年齡:a id="age">/a>br> 信息:a id="p0">/a>br> a id="p1">/a> /body> script> function show(){ var number= document.getElementById("number").value; var data= { data: JSON.stringify({ 'number': number }), } $.ajax({ url:"{{ url_for('history') }}", type:"post", data:data, dataType: 'json', success:function(data){ $(user).text(data.name); $(age).text(data.age); for(var i=0;idata.mess1.length;i++){ $("#p"+i).text(data.mess1[i]); } }, error:function(e){ alert("error"); } }) } /script> /html>
以上就可以簡(jiǎn)單的實(shí)現(xiàn)保存并讀取本地json文件。希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
標(biāo)簽:貴州 金華 赤峰 雙鴨山 克拉瑪依 陽(yáng)泉 臨汾 日照
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python 如何保存json文件并格式化》,本文關(guān)鍵詞 Python,如何,保存,json,文件,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。