我想在使用jsonpath_ng导航到JSON的某一特定部分后,添加一个节点到该部分,如下图所示。
import json
import jsonpath.ext as jspathExt
import pprint
jsStr = """
{
"service_group": "default",
"services": [
{
"service": "UserMgmt",
"servers": [
{
"server": "ServerA",
"ip_address": "192.168.1.1",
"port": "80"
},
{
"server": "ServerB",
"ip_address": "192.168.1.2",
"port": "80"
}
]
}
]
}
"""
js = json.loads(jsStr)
# create path
serviceName = "UserMgmt"
serverName = "ServerA"
pathExpr = f'$.services[?service="{serviceName}"].servers[?server = "{serverName}"]'
print(f"PathExpr: {pathExpr}")
serverExpr = jspathExt.parse(pathExpr)
m = serverExpr.find(js)
pprint.pprint(m[0].value)
这将给出以下输出。{'server': 'ServerA', 'ip_address': '192.168.1.1', 'port': '80'}
现在我希望能够添加 {'action_status': 'Success'}
到该节点,这样,:pprint.pprint(js)
的输出就会变成以下内容
{
"service_group": "default",
"services": [
{
"service": "UserMgmt",
"servers": [
{
"server": "ServerA",
"ip_address": "192.168.1.1",
"port": "80",
"action_status": "Success"
},
{
"server": "ServerB",
"ip_address": "192.168.1.2",
"port": "80"
}
]
}
]
}
我想过用 "更新 "的方法,但没能成功。如果您能提供任何帮助,我将感激不尽。
谢谢你的帮助。
阿米特
Jsonpath-ng和它的亲戚的文档非常少,所以可能有更好的方法,但这段代码应该能让你更接近。
m[0].value['action_status']='Success'
items = str(m).split('context=DatumInContext(value=')
final = items[-1].split(', path=Root(), context=None)))))]')[0]
final_js = json.loads(final.replace("'",'"'))
pprint.pprint(final_js)
输出(不是很好看... )
{'service_group': 'default',
'services': [{'servers': [{'action_status': 'Success',
'ip_address': '192.168.1.1',
'port': '80',
'server': 'ServerA'},
{'ip_address': '192.168.1.2',
'port': '80',
'server': 'ServerB'}],
'service': 'UserMgmt'}]}