使用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 ...
随机推荐
- mysql的优化(经典必看)
1.选取最适用的字段属性 MySQL可以很好的支持大数据量的存取,但是一般说来,数据库中的表越小,在它上面执行的查询也就会越快.因此,在创建表的时候,为了获得更好的性能,我们可以将表中字段的宽度设得尽 ...
- Java基础知识点总结笔记
面向对象的三大特性 继承:一般只能单继承,内部类实现多继承,接口可以多继承 封装:访问权限控制public>protected>包>private内部类也是一种封装 多态:编译时多态 ...
- Win10镜像升级到其他版本
写在前面 必须在MSDN下载VL版本系统,一定要是VL版本的. 下载镜像,将镜像中的sources/install.wim文件放到D盘下,可以放在其他路径,在命令中的路径就不同,再在D盘创建一个ima ...
- 批量启动关闭MS SQL 2005服务BAT
当装上了MSSQL2005后,内存的占用会变得很大.所以如果用一个批量处理来开启或关闭MSSQL2005所有的服务,那将会让我们的电脑更好使用.根据自己的经验,做出了下面两个批处理: 1.开启服务:( ...
- 阿里云linux挂载云盘
阿里云购买的第2块云盘默认是不自动挂载的,需要手动配置挂载上. 1.查看SSD云盘 sudo fdisk -l 可以看到SSD系统已经识别为/dev/vdb 2.格式化云盘 sudo mkfs.ext ...
- AcWing 275. 传纸条
#include<iostream> using namespace std ; ; *N][N][N]; int w[N][N]; int n,m; int main() { cin&g ...
- 【转】VS2017离线安装
[转自]https://www.cnblogs.com/feigao/p/8409606.html 第一步:下载离线安装包 https://www.visualstudio.com/zh-hans/d ...
- 题解 CF712C 【Memory and De-Evolution】
看到题我第一反应就是while循环 但是我竟然想正着推,失败,卡了十几分钟 后来我回来看到第三组测试数据 想到倒推 但是没坚持 于是我又卡了很久 过会我又回来想 AC了... 这个故事告诉我们,要努力 ...
- laravel Type error: Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request
第一种情况: 传递给 UrlGenerator 的第二个参数是 Request 实例 你传进去的是null, 可以检查 config文件夹下的配置文件是否有用到 url() 函数的,如果有,将 url ...
- webrtc博客收藏
<使用WebRTC搭建前端视频聊天室——入门篇><使用WebRTC搭建前端视频聊天室——信令篇><使用WebRTC搭建前端视频聊天室——点对点通信篇><使用W ...