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的更多相关文章

  1. 读取Json,并替换json中的指定字符

    string jsonfile = @"E:\history.json";//JSON文件路径 using (System.IO.FileStream file = new Fil ...

  2. mysql json_extract函数获取json字段中某个key的值

    参考:https://www.cnblogs.com/chuanzhang053/p/9139624.html json_extract函数可以获取json对象中指定key的值,用法:json_ext ...

  3. Python语言对Json对象进行新增替换操作

    # Json字符串进行新增操作import jsonimport os# os.path.dirname(__file__):表示当前目录path = os.path.join(os.path.dir ...

  4. python 学习(json)(转)

    Json简介:Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式.Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式.现在也常用于h ...

  5. python实现的json数据以HTTP GET,POST,PUT,DELETE方式页面请求

    一.JSON简介 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.易于人阅读和编写.同时也易于机器解析和生成.它基于JavaScript Programm ...

  6. python知识:json格式文本;异常处理;字符串处理;unicode类型和str类型转换

    python进程中的实例和json格式的字符串之间的映射关系是非常直接的,相当于同一个概念被编码成不同的表示: stream in json form ----json.loads(str)----- ...

  7. python编程 之 json包

    1,json是什么? JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写. 我的理解就是:json是一种统一的格式化的文件,比如,一个jso ...

  8. Python常用模块--json

    官方解释: JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.人类很容易读写.机器很容易解析和生成.它基于 JavaScript编程语言的一部分, 标准ECM ...

  9. Python datetime 转 JSON

    Python datetime 转 JSON Python 中将 datetime 转换为 JSON 类型,在使用 Django 时遇到的问题. 环境: Python2.7 代码: import js ...

随机推荐

  1. Linux安装Tomcat,解决不能访问Manager App

      在Windows环境中安装Tomcat时,只需要在Tomcat目录下/conf/tomcat-user.xml文件增加用户就可以了.在Linux系统中添加了username还是不能访问. 一.Li ...

  2. 模块一:shell 脚本基础

    一.shell脚本介绍 (一)脚本案例及介绍: #!/bin/bash LOG_DIR=/var/log ROOT_UID=0 if ["$UID -ne "$ROOT_UID&q ...

  3. python 数组格式转换

    格式转换 arr1 = [ {'name': 'jack', 'hobby': '西瓜'}, {'name': 'jack', 'hobby': '冬瓜'}, {'name': 'rose', 'ho ...

  4. Mike and strings

    Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can ...

  5. xshell如何将Windows文件上传到linux

    1.      首先先将你xshell配置好用户名及密码等,必须使用有权限下载的账号进行操作. 使用 yum provides */rz 这条命令,查看你系统自带的软件包的信息. 2.在输出的信息中可 ...

  6. 在 linux 中连接 mysql 数据库

    命令格式 mysql -h主机地址 -u用户名 -p用户密码 登录本机 mysql mysql -u用户名 -p用户密码 实例 TD - X1数据库:/opt/lampp/bin/mysql -u r ...

  7. java多线程技术

    如何实现线程 首先实现线程的两个方法:1.继承thread:2.实现接口Runnable类: 这边我就说一下第二种,因此第二种在开发中使用的比较多一些,能避免继承还是少避免继承. RunnableDe ...

  8. 滑动窗口-洛谷T1866(单调队列)

    咕咕咕 单调队列板子题 一.基本 1.单调队列: 特殊的双端队列,内部元素.分为最大队列(单调递增)和最小队列(单调递减)两种 二.应用 本题中:大部分单调队列优化的动态规划问题都和定长连续子区间的最 ...

  9. Codeforces Round #620 (Div. 2)E(LCA求树上两点最短距离)

    LCA求树上两点最短距离,如果a,b之间距离小于等于k并且奇偶性与k相同显然YES:或者可以从a先走到x再走到y再走到b,并且a,x之间距离加b,y之间距离+1小于等于k并且奇偶性与k相同也输出YES ...

  10. Js选择器总结

    一.原生JS选择器 JS选择器常用的有getElementById().getElementsByName().getElementsByTagName().getElementsByClassNam ...