使用python同时替换json多个指定key的value
1.如何同时替换json多个指定key的value
import json
from jsonpath_ng import parse def join_paths(regx_path,new_value,dict_replace):
"""
eg: join_paths(regx_path='$..host..namespace', new_value="9999999999", dict_replace=pydict)
:param regx_path: the path of replaced key
:param new_value: the new value of key to be replaced
:param dict_replace: the initial_dict that to be replaced
:return: dict
"""
data = dict_replace
jsonpath_expr = parse(regx_path)
str_path_list=[str(match.full_path) for match in jsonpath_expr.find(dict_replace)]
def cast_dict_path(path_list):
cast_list = []
for str_path in path_list:
path_split_list=str_path.split('.')
path = ''
for i in path_split_list:
if i.count('[')==1 and i.count(']')==1:
path=path+'[%s]'%eval(i)[0]
else:
path=path+"['%s']"%i
cast_list.append(path)
#[ "['role_parameters']['guest']['args']['data']['train_data'][0]['namespace']" ]
return cast_list
cast_paths=cast_dict_path(str_path_list)
for i in cast_paths:
if isinstance(new_value,str):
fullpath="data"+i+"='%s'"%new_value
abs_path=fullpath
exec(abs_path)
if isinstance(new_value,(int,list,float)):
fullpath = "data" + i + "={}".format(new_value)
abs_path=fullpath
exec(abs_path)
return data def muti_replace(rep_list,initial_dict:dict):
"""
format of rep_list:
[
(regx_path1 ,new_value1) ],
(regx_path2 ,new_value2 )
]
for example:
>> final_dict=muti_replace([('$..hetero_lr_0..eps',0.7777),('$..host..namespace',8888888)],initial_dict=pydict) initial_dict :the key need to replaced dict ,type dict
"""
dict_list=[]
for i in rep_list:
regx_path ,new_value=i[0],i[1]
dict_next=join_paths(regx_path,new_value,dict_replace=initial_dict)
dict_list.append(dict_next)
for k in dict_list:
initial_dict.update(k)
print(json.dumps(initial_dict,indent=5))
return initial_dict if __name__ == '__main__': final_dict=muti_replace([('$..hetero_lr_0..eps',0.7777),('$..host..namespace',8888888)],initial_dict=pydict)
测试数据:
{
"initiator": {
"role": "guest",
"party_id":
},
"job_parameters": {
"work_mode":
},
"role": {
"guest": [ ],
"host": [ ],
"arbiter": [ ]
},
"role_parameters": {
"guest": {
"args": {
"data": {
"train_data": [
{
"name": "breast_guest",
"namespace": "breast_guest"
}
]
}
},
"dataio_0": {
"with_label": [true],
"label_name": ["y"],
"label_type": ["int"],
"output_format": ["dense"],
"missing_fill": [true],
"outlier_replace": [true]
},
"feature_scale_0": {
"method": ["min_max_scale"]
},
"hetero_feature_binning_0": {
"method": ["quantile"],
"compress_thres": [],
"head_size": [],
"error": [0.001],
"bin_num": [],
"cols": [-],
"adjustment_factor": [0.5],
"local_only": [false],
"transform_param": {
"transform_cols": [-],
"transform_type": ["bin_num"]
}
},
"hetero_feature_selection_0": {
"select_cols": [-],
"filter_methods": [[
"unique_value",
"iv_value_thres",
"coefficient_of_variation_value_thres",
"iv_percentile",
"outlier_cols"
]],
"local_only": [false],
"unique_param": {
"eps": [1e-]
},
"iv_value_param": {
"value_threshold": [1.0]
},
"iv_percentile_param": {
"percentile_threshold": [0.9]
},
"variance_coe_param": {
"value_threshold": [0.3]
},
"outlier_param": {
"percentile": [0.95],
"upper_threshold": []
}
},
"evaluation_0": {
"eval_type": ["binary"],
"pos_label": []
}
},
"host": {
"args": {
"data": {
"train_data": [
{
"name": "breast_host",
"namespace": "breast_host"
}
]
}
},
"dataio_0": {
"with_label": [false],
"output_format": ["dense"],
"outlier_replace": [true]
},
"feature_scale_0": {
"method": ["standard_scale"],
"need_run": [false]
},
"hetero_feature_binning_0": {
"method": ["quantile"],
"compress_thres": [],
"head_size": [],
"error": [0.001],
"bin_num": [],
"cols": [-],
"adjustment_factor": [0.5],
"local_only": [false],
"transform_param": {
"transform_cols": [-],
"transform_type": ["bin_num"]
}
},
"hetero_feature_selection_0": {
"select_cols": [-],
"filter_methods": [[
"unique_value",
"iv_value_thres",
"coefficient_of_variation_value_thres",
"iv_percentile",
"outlier_cols"
]],
"local_only": [false],
"unique_param": {
"eps": [1e-]
},
"iv_value_param": {
"value_threshold": [1.0]
},
"iv_percentile_param": {
"percentile_threshold": [0.9]
},
"variance_coe_param": {
"value_threshold": [0.3]
},
"outlier_param": {
"percentile": [0.95],
"upper_threshold": []
}
},
"evaluation_0": {
"need_run": [true]
}
}
},
"algorithm_parameters": {
"feature_scale_0": {
"need_run": true
},
"hetero_feature_binning_0": {
"need_run": true
},
"hetero_feature_selection_0": {
"need_run": true
},
"hetero_lr_0": {
"penalty": "L2",
"optimizer": "rmsprop",
"eps": 1e-,
"alpha": 0.01,
"max_iter": ,
"converge_func": "diff",
"batch_size": -,
"learning_rate": 0.15,
"init_param": {
"init_method": "random_uniform"
},
"cv_param": {
"n_splits": ,
"shuffle": false,
"random_seed": ,
"need_cv": false
}
}
}
}
使用python同时替换json多个指定key的value的更多相关文章
- 读取Json,并替换json中的指定字符
string jsonfile = @"E:\history.json";//JSON文件路径 using (System.IO.FileStream file = new Fil ...
- mysql json_extract函数获取json字段中某个key的值
参考:https://www.cnblogs.com/chuanzhang053/p/9139624.html json_extract函数可以获取json对象中指定key的值,用法:json_ext ...
- Python语言对Json对象进行新增替换操作
# Json字符串进行新增操作import jsonimport os# os.path.dirname(__file__):表示当前目录path = os.path.join(os.path.dir ...
- python 学习(json)(转)
Json简介:Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式.Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式.现在也常用于h ...
- python实现的json数据以HTTP GET,POST,PUT,DELETE方式页面请求
一.JSON简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programm ...
- python知识:json格式文本;异常处理;字符串处理;unicode类型和str类型转换
python进程中的实例和json格式的字符串之间的映射关系是非常直接的,相当于同一个概念被编码成不同的表示: stream in json form ----json.loads(str)----- ...
- python编程 之 json包
1,json是什么? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写. 我的理解就是:json是一种统一的格式化的文件,比如,一个jso ...
- Python常用模块--json
官方解释: JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.人类很容易读写.机器很容易解析和生成.它基于 JavaScript编程语言的一部分, 标准ECM ...
- Python datetime 转 JSON
Python datetime 转 JSON Python 中将 datetime 转换为 JSON 类型,在使用 Django 时遇到的问题. 环境: Python2.7 代码: import js ...
随机推荐
- C++ 获取当前正在执行的函数的相关信息(转)
该功能用在日志打印中 原文地址:C++ 获取当前正在执行的函数的相关信息
- js及jsp.java查错的几种方式
一.js 1.console.log("你想输出的内容"); 2.alert("你想输出的内容"); 3.debugger;(记得打开F12) 4.快速找到js ...
- LED Decorative Light Supplier - LED Neon Application: 5 Advantages
In the past 100 years, lighting has gone a long way. LED decorative lighting is now designed to meet ...
- Centos7添加软链接
1.pycharm添加软连接: 命令行模式中输入命令: ln -s /root/pycharm-2018.1/bin/pycharm.sh /usr/bin/pycharm ps:代码中/root/p ...
- my bug of VG algorithm
def visibility_graph(series): g = nx.Graph() # convert list of magnitudes into list of tuples that h ...
- 5G套餐资费或为199元至599元,高昂价格会阻碍大众使用热情吗?
近段时间,运营商各种谜一般的操作让其走上舆论的风口浪尖,成为人们口诛笔伐的对象.比如在前段时间,运营商相继宣布要取消"达量降速版畅享套餐",对用户的权益造成巨大冲击,引发了网络热议 ...
- 删除空目录命令 - rmdir
(1) 命令名称:rmdir (2) 英文原意:remove empty directories (3) 命令所在路径:/bin/rmdir (4) 执行权限:所有用户 (5) 功能描述:删除空目录( ...
- 【转】C# Application.DoEvent()的作用
Application.DoEvents()的作用:处理所有的当前在消息队列中的Windows消息. private void button1_Click(object sender, EventAr ...
- js -- 时间转年月日
/** * 时间转年月日 * @param sdate 开始的时间 * @param edate 结束的时间 * @returns {*} */ function day2ymrStr2(sdate, ...
- e.printStackTrace()打印在哪里以及如何e.printStackTrace()的内容打印在日志中
1.e.printStackTrace()打印在哪里 在catch中的e.printStackTrace()将打印到控制台 2.e.printStackTrace()打印的内容是什么 如下代码: im ...