0

I'm trying to count number of nested JSON array elements grouped by parent index using MySQL 8 JSON type field. My JSON string looks like

{
  "a": [
    {
      "b": [
        1,
        2,
        3
      ]
    },
    {
      "b": [
        1
      ]
    }
  ]
}

I'm trying to get the count of elements under "b" key for each "a" element. I need an output similar to:

{0: 3, 1: 1}

Meaning that a[0] has 3 elements under "b", while a[1] has 1.

This query counts total number of "b" elements across all "a"s (yields 4):

select JSON_LENGTH(json->>'$.a[*].b[*]') from myTable

Is it possible to somehow group it by a's index?

Thank you!

1 Answer 1

3

One option is JSON_TABLE and JSON_OBJECTAGG:

SELECT
  JSON_OBJECTAGG(
    `rowid` - 1,
    JSON_LENGTH(`count`)
  )
FROM JSON_TABLE(
  '{"a":[{"b":[1,2,3]},{"b":[1]}]}',
  '$.a[*]'
  COLUMNS(
    `rowid` FOR ORDINALITY,
    `count` JSON PATH '$.b'
  )
) `der`;

See db-fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.