Search code examples
pythonjsonjsonpathjsonpath-ng

How do we use regex filter in jsonpath_ng python, it treats / as SORT Direction. any alternative?


I'm trying to find the Worker whose Worker Value contains the number 880099 as substring. Here i'm trying to find priyanka's details using her employee ID.

My Code .

json_data = json.loads(json_string)
from jsonpath_ng.ext import parser
query = r'$[?(@.Worker =~ /.*?880099.*/i)]'
for match in parser.parse(query).find(json_data):
   
   

JSON DATA : [{ "Time Off Entry": "1 Feb, 2021 - 1 Days (Divakar (77877))", "Worker": "Divakar (77877)", "Request Type": "Time Off Request", "Time Off/Absence Table": "IND Annual Time Off", "Type": "Annual Leave", "Entered On": 1611187200000, "Approval Date": 1611187200000, "Time Off Date": 1612137600000, "Approved": 1, "Unit of Time": "Days" }, { "Time Off Entry": "1 Feb, 2021 - 1 Days (Priyanka (880099))", "Worker": "Priyanks (880099)", "Request Type": "Time Off Request", "Time Off/Absence Table": "IND Sick/Casual Time Off", "Type": "Sick/Casual Leave", "Entered On": 1612310400000, "Approval Date": 1612310400000, "Time Off Date": 1612137600000, "Approved": 1, "Unit of Time": "Days" }]


Solution

  • Your jsonpath-ng syntax for the regex-comparison is not correct. Try quotes around the pattern instead like this:

    parser.parse('$[?(@.Worker =~ ".*880099.*")]').find(json_data)]
    

    Full sample:

    import json
    json_string =  "[{ \"Time Off Entry\": \"1 Feb, 2021 - 1 Days (Divakar (77877))\", \"Worker\": \"Divakar (77877)\", \"Request Type\": \"Time Off Request\", \"Time Off/Absence Table\": \"IND Annual Time Off\", \"Type\": \"Annual Leave\", \"Entered On\": 1611187200000, \"Approval Date\": 1611187200000, \"Time Off Date\": 1612137600000, \"Approved\": 1, \"Unit of Time\": \"Days\" }, { \"Time Off Entry\": \"1 Feb, 2021 - 1 Days (Priyanka (880099))\", \"Worker\": \"Priyanks (880099)\", \"Request Type\": \"Time Off Request\", \"Time Off/Absence Table\": \"IND Sick/Casual Time Off\", \"Type\": \"Sick/Casual Leave\", \"Entered On\": 1612310400000, \"Approval Date\": 1612310400000, \"Time Off Date\": 1612137600000, \"Approved\": 1, \"Unit of Time\": \"Days\" }]"
    json_data = json.loads(json_string)
    
    from jsonpath_ng.ext import parser
    query = [x.value for x in parser.parse('$[?(@.Worker =~ ".*880099.*")]').find(json_data)]
    print(json.dumps(query))