1.将json文件读取后,修改,再写入
#output.json文件
{
"tests_num": 11,
"failures": 0,
"testsuites": {
"testsuite": {
"testcases": {
"test1": {
"result": "good",
"description": "Orin1、Orin2升级",
"message": ""
},
"test2": {
"result": "good",
"description": "soc1(172.31.3.80)是否可以通过ssh登录",
"message": ""
}
}
}
}
}
import json
import jsonpath
output = 'output.json'
with open(output, 'r', encoding='utf-8') as f_write:
# load将文件流转成字典
data = json.load(f_write)
# jsonpath不管位置,选择所有符合条件的节点
jsonpath.jsonpath(data, '$..test1')[0]['result'] = "fail"
with open(output, 'w+', encoding='utf-8') as f_write:
f_write.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False))
2.修改json字符串,并写入文件
import json
import jsonpath
output = '''
{
"tests_num": 11,
"failures": 0,
"testsuites": {
"testsuite": {
"testcases": {
"test1": {
"result": "good",
"description": "Orin1、Orin2升级",
"message": ""
},
"test2": {
"result": "good",
"description": "soc1(172.31.3.80)是否可以通过ssh登录",
"message": ""
}
}
}
}
}
'''
# loads将json字符串转成字典
data = json.loads(output)
# jsonpath不管位置,选择所有符合条件的节点
jsonpath.jsonpath(data, '$..test1')[0]['result'] = "fail"
with open('output.json', 'w+', encoding='utf-8') as f_write:
f_write.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False))