在Python中如何使用过滤器更新jsonpath处的节点?

问题描述 投票:0回答:1

我想通过过滤更新 json 路径处的节点(例如,带有“[@.field]”部分的 json 路径)。

我当前对 jsonpath_ng 的尝试失败了:

import jsonpath_ng.ext
import jsonpath_ng
from hashlib import md5

# try several ways to transform {"a": {"b": "c"}} into {"a": {1: 2}}
for jpath_str in ["$.a", "$[?(@.b)]", "$.a.b.`parent`"]:
    for jp_lib in [jsonpath_ng, jsonpath_ng.ext]:
        obj = json.loads('{"a": {"b": "c"}}')
        print(f"jp_lib={jp_lib.__name__:<15} json_path_str={jpath_str:<15}", end="\t")
        try:

            # find a node, and then attempt to update it
            jpath = jp_lib.parse(jpath_str)
            matches = jpath.find(obj)
            if not matches:
                print("--> Not found")
                continue
            for match in matches:
                print(f"match={md5(str(match).encode()).hexdigest()[:-10]}", end="\t")
            jpath.update(obj, {1:2})
            print(f"--> result={obj}", end="\t")
            if "b" in obj['a']: print(" -->Update failed silently", end="\t")

        except Exception as ex:
            print(f"--> exception={type(ex).__name__}({ex})", end="\t")
        print()

输出:

jp_lib=jsonpath_ng     json_path_str=$.a                match=6d6c26aced0709ca568e84    --> result={'a': {1: 2}}    
jp_lib=jsonpath_ng.ext json_path_str=$.a                match=6d6c26aced0709ca568e84    --> result={'a': {1: 2}}    
jp_lib=jsonpath_ng     json_path_str=$[?(@.b)]          --> exception=JsonPathLexerError(Error on line 1, col 2: Unexpected character: ? )  
jp_lib=jsonpath_ng.ext json_path_str=$[?(@.b)]          match=6de1848d9db98d7d1c6766    --> result={'a': {'b': 'c'}}     -->Update failed silently  
jp_lib=jsonpath_ng     json_path_str=$.a.b.`parent`     match=6d6c26aced0709ca568e84    --> exception=NotImplementedError() 
jp_lib=jsonpath_ng.ext json_path_str=$.a.b.`parent`     match=6d6c26aced0709ca568e84    --> exception=NotImplementedError() 
python jsonpath
1个回答
0
投票

不同的库:

import jsonpath

obj = json.loads('{"a": {"b": "c"}}')

matches = jsonpath.jsonpath(obj, "$[?(@.b)]")
for match in matches:
    match["b"] = {1: 2}
print(obj) # prints: {'a': {'b': {1: 2}}}
© www.soinside.com 2019 - 2024. All rights reserved.