h2non / jsonpath-ng

Finally, a JSONPath implementation for Python that aims to be standard compliant. That's all. Enjoy!
Apache License 2.0
593 stars 86 forks source link

jsonpath-ng does not recognize same expressions as jsonpath.com and jsonpath-python #124

Open dcsoft4 opened 1 year ago

dcsoft4 commented 1 year ago

Depending on how the expressions are formatted, jsonpath-ng (1.5.3) does not always find the desired results the same as jsonpath.com and the jsonpath-python library.

import jsonpath_ng

data = {
  "keyframeMap": {
    "1": {
      "infoMap": {
        "main": {
          "colorCodeMap": {
            "1": {
              "hex": "#ffc284"
            },
            "2": {
              "hex": "#001384"
            }
          }
        },
        "alt": {
          "colorCodeMap": {
            "1": {
              "hex": "#00ff00"
            },
            "2": {
              "hex": "#808080"
            }
          }
        }
      }
    },
    "2": {
      "infoMap": {
        "main": {
          "colorCodeMap": {
            "1": {
              "hex": "#012345"
            },
            "2": {
              "hex": "#00ffff"
            }
          }
        },
        "alt": {
          "colorCodeMap": {
            "1": {
              "hex": "#000000"
            },
            "2": {
              "hex": "#ffffff"
            }
          }
        }
      }
    }
  }
}

def test_jsonpath_ng(expr, data) -> bool:
    try:
        res = [match.value for match in jsonpath_ng.parse(expr).find(data)]
    except:
        res = False

    return res and len(res)     # successful if a non-empty list was returned (some data was found)

def main():
    expr_notations = {
        # jsonpath-ng: bad (no match)
        # jsonpath.com ok
        'bracket': '$.keyframeMap[*].infoMap[main].colorCodeMap[1]',
        'dot': '$.keyframeMap.*.infoMap.main.colorCodeMap.1',

        # jsonpath-ng: ok
        # jsonpath.com ok
        'quoted_bracket': '$.keyframeMap["*"].infoMap["main"].colorCodeMap["1"]',

        # jsonpath_ng ok
        # jsonpath.com bad (no match)
        'quoted_dot': '$.keyframeMap."*".infoMap.main.colorCodeMap."1"',
        'quoted_dot2': '$.keyframeMap.*.infoMap.main.colorCodeMap."1"',
    }

    assert (not test_jsonpath_ng(expr_notations['bracket'], data))
    assert (not test_jsonpath_ng(expr_notations['dot'], data))
    assert (test_jsonpath_ng(expr_notations['quoted_bracket'], data))
    assert (test_jsonpath_ng(expr_notations['quoted_dot'], data))
    assert (test_jsonpath_ng(expr_notations['quoted_dot2'], data))

if __name__ == "__main__":
    main()