python操作json的封装,可以读取和设置指定的key的值,直接上代码:
# coding=utf-8
""" json工具类 """
import os
import json
import sys
import getopt
def store_json(data, file_path):
""" 保存json到文件 """
with open(file_path, 'w') as fw:
# 将字典转化为字符串
# json_str = json.dumps(data)
# fw.write(json_str)
# 上面两句等同于下面这句
json.dump(data, fw)
def load_json(file_path):
""" load json data from file """
if not os.path.exists(file_path):
return
with open(file_path, 'r') as f:
data = json.load(f)
return data
# def set_value(file_path, key, value):
# target_j = load_json(file_path)
# if not target_j:
# target_j = {}
# target_j[key] = value
# store_json(target_j, file_path)
def set_json_value(data, key, value):
if key.endswith("."):
key = key[0:(len(key) - 1)]
if key.find(".") > -1:
f_index = key.index(".")
key1 = key[0:f_index]
key2 = key[(f_index + 1):len(key)]
if not key1 in data:
data1 = {}
else:
data1 = data[key1]
return set_json_value(data, key1, set_json_value(data1, key2, value))
# data[key1] = data1
# return data
# print(json.dumps(data))
else:
if not data or (not type(data).__name__ == 'dict'):
data={}
# print("key:"+key)
# print("data:"+key)
data[key] = value
return data
def set_value(file_path, key, value):
target_j = load_json(file_path)
if not target_j:
target_j = {}
data = set_json_value(target_j, key, value)
# print(json.dumps(data))
store_json(data, file_path)
def get_json_value(data, key):
if not data:
return None
if key.endswith("."):
key = key[0:len(key) - 1]
if key.find(".") > -1:
f_index = key.index(".")
key1 = key[0:f_index]
key2 = key[(f_index + 1):len(key)]
if not key1 in data:
return None
return get_json_value(data[key1], key2)
else:
if not key in data:
return None
return data[key]
def get_value(file_path, key):
target_j = load_json(file_path)
if not target_j:
target_j = {}
return get_json_value(target_j, key)
def main():
key_name = ""
file_path = ""
value = ""
option = ""
try:
opts, args = getopt.getopt(sys.argv[1:], "hf:k:v:p:", ["file=", "key=", "value=", "option="])
except getopt.GetoptError:
print('jsonutil.py -f <file> -p <operation> -k <key> -v <value>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('jsonutil.py -f <file> -p <operation> -k <key> -v <value>')
sys.exit()
elif opt in ("-f", "--file"):
file_path = arg
elif opt in ("-k", "--key"):
key_name = arg
elif opt in ("-v", "--value"):
value = arg
elif opt in ("-p", "--option"):
option = arg
if option == "set":
set_value(file_path, key_name, value)
# target_j = load_json(file_path)
# if not target_j:
# target_j = {}
# target_j[key_name] = value
# store_json(target_j, file_path)
else:
if not os.path.exists(file_path):
return
else:
# target_j = load_json(file_path)
# print(target_j[key_name])
print(get_value(file_path, key_name))
if __name__ == "__main__":
main()
json:{"a":{"name":"lisi","age":10}}
读取示例: python jsonutil.py -f test.json -p get -k a.name
设置值示例: python jsonutil.py -f test.json -p get -k a.name -v zhangsan