0

I've got this very simple json :

{
    "authors": [
        {
            "id": 1,
            "name": "Douglas Adams"
        },
        {
            "id": 2,
            "name": "John Doe"
        }
    ],
    "books": [
        {
            "name": "The Hitchhiker's Guide to the Galaxy",
            "author_id": 1
        }
    ]
}

I would like to request the name of the author of "The Hitchhiker's Guide to the Galaxy". I've tried this JSON path but it doesn't work:

$.authors[?(@.id == $.books[?(@.name == "The Hitchhiker's Guide to the Galaxy")].author_id)].name

All online tools I tried indicate a syntax error which seems due to the presence of a JSON path inside my filter.

Could anyone please help me figure out what's wrong and what is the right syntax?

Thanks!

1 Answers1

0

When you running this filter

$.books[?(@.name == "The Hitchhiker's Guide to the Galaxy")].author_id

it returns an array instead of a value:

[
  1
]

Syntax error occurs when you pass an array to compare with the value of id:

$.authors[?(@.id == {the array value}].author_id)].name

However, you may not be able to extract the value using JSONPath, depends on the language you are using. See Getting a single value from a JSON object using JSONPath

Bemn
  • 1,291
  • 1
  • 7
  • 22
  • Thanks for your reply @Bemn I'm going to see whether I can fetch the first value of the array with the jsonpath implementation I use. – Nicolas Talfer Aug 24 '22 at 08:35