天天看點

Python學習筆記 --- python實作修改json檔案

基本原理就是通過讀取檔案,将json資料讀取出來,然後進行修改,再寫回檔案中。

# -*- coding:utf-8 -*-
import json
def process_json(input_json_file, output_json_file):
    file_in = open(input_json_file, "r")
    file_out = open(output_json_file, "w")
    # load資料到變量json_data
    json_data = json.load(file_in)
    print json_data
    print "after update  --->"
    print type(json_data)
    # 修改json中的資料
    json_data["job"] = "hahah"
    print json_data
    
    # 将修改後的資料寫回檔案
    file_out.write(json.dumps(json_data))
    file_in.close()
    file_out.close()
 
process_json("../jsonfile/mysql2hive_templet.json","../jsonfile/mysql2hive_instance.json")