Search code examples
jsonjmeterjsonpathjson-path-expression

Json query that returns parent element and child data with condition?


I've this JSON (I know it's not a very conventional JSON ;) )

{ 
   "2958114":{"stockOnline": 305 }, 
   "2958113": {"stockOnline": 2}, 
   "2958115": {"stockOnline": 0} 
}

I want to extract all line with stockOnline attribute <> 0 with a JSON query (I use the https://jsonpath.com/ to test on line)

I try this query $.*[?(@.stockOnline != 0)] that returns all stockOnline values but not the complete line.

I try other queries without success.

have you any ideas ?

Thanks and regards

I try this query $.[?(@.stockOnline != 0)]* that returns all stockOnline values but not the complete line.


Solution

  • There are no "lines" in JSON, only objects, arrays, attributes and their values.

    If you want to have "lines" where stockOnline is not 0 - you will have to go for JSR223 PostProcessor and a custom Groovy code like:

    def json = new groovy.json.JsonSlurper().parse(prev.getResponseData())
    
    def entries = json.findAll(entry -> entry.getValue().stockOnline != 0)
    
    entries.each { entry ->
        log.info('"' + entry.getKey() + '":' + new groovy.json.JsonBuilder(entry.getValue()).toString())
    }
    

    Demo:

    enter image description here