Steve Lloyd
Steve Lloyd

Reputation: 949

Querying a nested JSON field in MySQL

I have a JSON field in MySQL with the following structure:

{
    "menu": {
        "reports": {
            "checked": 1
        }
    },
    "survey": {
        "5": {
            "checked": 1
        }
    },
    "location": {
        "208": {
            "checked": 1,
            "satisfied": 1
        }
    }
}

I want to get records where survey.5.checked=1.
The following works fine:

select email,filters,filters->'$.survey' as survey from users

and this works:

select email,filters,filters->'$.survey.reports' as reports from users

but this fails:

select email,filters,filters->'$.survey.5' as survey from users

and this fails:

select email,filters,filters->'$.survey.5.checked' as survey from users

How can I query the JSON field for records where survey.5.checked = 1 ? Are you not able to use numbers as keys in your JSON structure?

Upvotes: 0

Views: 78

Answers (1)

GMB
GMB

Reputation: 222432

You need to double-quote the all-digit key (similarily, if the key contains spaces, it also needs to be double-quoted).

select email, filters, filters -> '$.survey."5".checked' from users

If you actually want to filter:

select email, filters
from users
where filters -> '$.survey."5".checked' = 1

Upvotes: 1

Related Questions