使用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 ...
随机推荐
- 让Surface Shader不受光照的明暗影响
直接上码 Shader "Custom/3DVideo" { Properties { _Color (,,,) _MainTex ("Albedo (RGB)" ...
- markdown文本编辑学习笔记2
目录 1.删除线 2.无序列表 4 todo list 5分割符号 6 TOC自动生成目录 7 插入代码块 8 斜体.粗体.删除线.下划线.背景高亮 markdown编辑公式 1.删除线 ~~要删除的 ...
- 采用PHP实现”服务器推”技术的聊天室
传统的B/S结构的应用程序,都是采用”客户端拉”结束来实现客户端和服务器端的数据交换. 本文将通过结合Ticks(可以参看我的另外一篇文章:关于PHP你可能不知道的-PHP的事件驱动化设计),来实 ...
- 阿里云安装Nginx+vue项目部署
阿里云安装Nginx+vue项目部署 nginx安装包下载 http://nginx.org/en/download.html nginx安装 首先先安装PCRE pcre-devel 和Zlib,因 ...
- K3/Cloud点击按钮打开第三方URL
public override void AfterBarItemClick(BOS.Core.DynamicForm.PlugIn.Args.AfterBarItemClickEventArgs e ...
- PP: Overviewing evolution patterns of egocentric networks by interactive construction of spatial layouts
Problem: get an overall picture of how ego-networks evolve is a common challenging task. Existing te ...
- linux 命令 mkdir
mkdir -p 如果要创建目录A并创建目录A的子目录B,没有用-p的情况下mkdir 逐个的创建目录(mkdir A,mkdir A/B); 如果用-p 可以直接创建2个目录 mkdir -p A/ ...
- (转)GC ROOTS
还是英文的技术博客更给力,更清楚,本人懒,没有翻译. In your specific example, in any managed environment, Person is not a GC ...
- Android 开发 ThreadPool(线程池) 总结
本文是介绍线程池的基础篇. 一.线程池的作用 创建异步线程的弊端: 1.每次new Thread创建对象,导致性能变差. 2.缺乏统一的管理,可能导致无限制的线程运行,严重的后果就是OOM 或者死机. ...
- python如何离线装包 离线如何部署python环境
1,安装python windows: 我用的是python3.6.6.exe安装包,需要提前下载好 ubuntu: 自带的python,如果是ubuntu18.04的话,自带的应该是3.6.8 2, ...