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之温故知新1

    1.touch命令的使用 2.使用(cd -)可以在上次使用的目录来回切换 3.ls通配符的使用*代表任意字符和任意个字符, ?代表任意一个字符, [12345]中的任意一个字符, [1-5]中的任意 ...

  2. JUC-ThreadPool线程池

    一.为什么用线程池 例子:10年前单核CPU电脑,假的多线程,像马戏团小丑玩多个球,CPU需要来回切换. 现在是多核电脑,多个线程各自跑在独立的CPU上,不用切换效率高. 线程池的优势: 线程池做的工 ...

  3. cookie 与 session区别

    cookie 与 session 是网页开发中常用的信息存储方式.Cookie是在客户端开辟的一块可存储用户信息的地方:Session是在服务器内存中开辟的一块存储用户信息的地方.JavaScript ...

  4. flask入门(一)

    flask是一个轻量级的框架,据说跟django跟比是真的轻. 首先要先配置一个虚拟环境,flask项目需要在那个虚拟环境里运行,这里需要用的venv库实在python3里的标准库,不过有的linux ...

  5. 题解 SP27102/UVA1747 【Swap Space】

    SP27102 [Swap Space] 双倍经验:UVA1747 Swap Space 用(a,b)表示每个硬盘的原容量和新文件系统下的容量.分两种情况考虑:a≤b和a>b 第一类a≤b格式化 ...

  6. QT5.1+中文乱码问题

    原文连接:https://blog.csdn.net/liyuanbhu/article/details/72596952 QT中规定 QString 的 const char* 构造函数是调用 fr ...

  7. 使用鼠标左键事件实现VR中的Eye Gaze Input

    1.光标以及光标动画的显示 using System.Collections; using System.Collections.Generic; using UnityEngine; using U ...

  8. mysql数据库事务的操作与理解

    --------------------事务----------------------------------------------查询mysql事务隔离级别1.查看当前会话隔离级别select ...

  9. jQuery实现TAB选项卡切换特效简单演示

    本文实例为大家分享jQuery实现TAB选项卡切换特效,供大家参考,具体内容如下 1.tab切换 on ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 ...

  10. Flink架构(五)- 检查点,保存点,与状态恢复

    检查点,保存点,与状态恢复 Flink是一个分布式数据处理系统,这种场景下,它需要处理各种异常,例如进程终止.机器故障.网络中断等.因为tasks在本地维护它们的state,Flink必须确保在出现故 ...