The value method of modifying JSON file by Python


When we do engineering, we need to listen to the JSON file and deal with it according to the key-value value value in the JSON file. For this purpose, a python script to modify the JSON file is written for subsequent invocation of the project.

The code is as follows:

# coding = UTF-8 /// Setting Text Format
import os,sys
import json
def get_new_json(filepath,key,value):
	key_ = key.split(".")
	key_length = len(key_)
	with open(filepath, 'rb') as f:
		json_data = json.load(f)
		i = 0
		a = json_data
		while i < key_length :
			if i+1 == key_length :
				a[key_[i]] = value
				i = i + 1
			else :
				a = a[key_[i]]
				i = i + 1
	return json_data
def rewrite_json_file(filepath,json_data):
	with open(filepath, 'w') as f:
if __name__ == '__main__':
	key = sys.argv[1]
	value = int(sys.argv[2])
	json_path = sys.argv[3]
	m_json_data = get_new_json(json_path,key,value)	

Operational examples:

python a.b.c 999 /home/cabin/example.json

That is to say, the value corresponding to key value A.B.C in example.json is changed to 999.

The above article uses Python to modify the value method of JSON file is the whole content shared by the editor. I hope to give you a reference, and I hope you will support developpaer more.