replaceJsonData.py 1.04 KB
# -*- coding: utf-8 -*-

# @Time    : 2021/9/8 16:45
# @Author  : Ljq
# @File    : replaceJsonData.py
# @Software: PyCharm

"""
使用无嵌套的json格式数据,对嵌套的json内部的值的进行替换
"""

def replaceJsonData(json={},data={}):
    for i in json.keys():
        if i in data.keys() and type(json[i]) != dict and type(json[i]) != list:
            json[i]=data[i]
        elif type(json[i]) == dict:
            json[i] = replaceJsonData(json=json[i],data=data)
        elif type(json[i]) == list:
            for list_child_index in range(len(json[i])):
                if type(json[i][list_child_index]) == dict:
                    json[i][list_child_index] = replaceJsonData(json=json[i][list_child_index], data=data)
                else:
                    if i in data.keys():
                        json[i] = data[i]
    return json

# json = {"a":"1","b":[{"c":"1"},{"c":2}],"d":[1],"e":"1","f":{"g":1},"h":1,"i":[1]}
# data = {"a":"a","c":"c","e":"e","d": {"d1":"d1"},"g":"g","h":"h"}
# print(replaceJsonData(json=json,data=data))