python 读取和操作json

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值