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

Wanted an example of arithmetic expressions #170

Closed pranav121322 closed 1 month ago

pranav121322 commented 4 months ago
import json
from jsonpath_ng import jsonpath, parse
import jsonpath_ng.ext.arithmetic

# Example JSON data
json_data = '''
{
    "Keys": [
        {"Format": "A", "Subtype": "A1"},
        {"Format": "A", "Subtype": "A2"},
        {"Format": "B", "Subtype": "A1"}
    ]
}
'''

# Parse the JSON data
data = json.loads(json_data)

# Define the JsonPath expression
expression = parse("$.concat($.Keys[0].Format, $.Keys[0].Subtype)")
**# wanted to get AA1**

# Evaluate the expression for the first element
result = [match.value for match in expression.find(data)]
print("Concatenated value for the first element:", result[0])
michaelmior commented 1 month ago

Firstly, you'll have to import parse from jsonpath_ng.ext. Second, $.concat is referring to a key named "concat" in your JSON object. If you just want to concatenate those two values, you can use the expression "$.Keys[0].Format + $.Keys[0].Subtype".

I'm going to close this, but feel free to reopen if you have more questions.