Skip to content

When JSON Path Matching returns value or values as an array

nirmalchandra edited this page Aug 18, 2019 · 6 revisions

Introduction

When JSON path is used for finding one or more dynamic elements in an array, it always returns the matching result as an array. This means even it finds just one matching element, it returns that element as an array.

This makes it difficult to reuse that leaf element as a single field or single value.

e.g. given a JSON response as below,

{
    "results": [
        {
            "id": 1,
            "name": "Foo"
        },
        {
            "id": 2,
            "name": "Bar"
        }
    ]
}

when, we search for Foo and find its id using below Jayway JSON Path,

$.results[?(@.name == 'Foo')].id

it returns,

[
   1
]

Similarly,

$.results[?(@.id == 2)].name

returns,

[
   "Bar"
]

and

$.results[?(@.id > 0)].name

returns

[
   "Foo",
   "Bar"
]

Pick the value from single-value array

Pick a value from multi-value array

Conclusion

Blogs

Clone this wiki locally