使用 jsonpath_ng 添加新节点

Adding a new node using jsonpath_ng

我想在使用 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"
        }
      ]
    }
  ]
}

我研究过使用 "update" 方法,但无法使用。如果您能提供任何帮助,我将不胜感激。

谢谢,

阿米特

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'}]}