1

I have a Postgres statement that returns extracts/iterates over a json blob in the value column of a table. I am able to get a count one level deep using the query below but I can't count any deeper. I was using:

select jsonb_array_length(value -> 'team') as team_count

This returns the proper count but I cant seem to leverage this to count the names under each team.

In a perfect world I would my results to return 4 lines of results like this(title and a matching count of names):

Product Owner, 2
Technical Product Manager, 2
Data Modeler, 0 
Engineer, 0

How would I go about amending this query to give me the count of names under team? I tried all sorts of stuff but nothing that got me close.

Sample Json is below.

"team":[
  {
     "title":"Product Owner",
     "names":[
         "John Smith",
         "Jane Doe"
     ]
  },
  {
     "title":"Technical Project Manager",
     "names":[
         "Fred Flintstone",
         "Barney Rubble"
     ]
  },
  {
     "title":"Data Modeler"
  },
  {
     "title":"Engineer"
  }
3
  • Not sure what you mean with "title elements under team" . Are you maybe looking for jsonb_array_length(value -> 'team')? That count's the number of elements in the "team" array (regardless if the objects inside that array have a key named title) Commented Mar 18, 2020 at 20:10
  • @a_horse_with_no_name - I edited my question to add more clarity, trying your suggestion now. Commented Mar 18, 2020 at 20:20
  • @a_horse_with_no_name - this might be it... looking at this further Commented Mar 18, 2020 at 20:22

1 Answer 1

2

You seem to be looking for

SELECT
   role -> 'title' AS team_role,
   jsonb_array_length(role -> 'names') AS member_count
FROM jsonb_array_elements(value -> 'team') AS team(role)
Sign up to request clarification or add additional context in comments.

1 Comment

this was it.. Since we came from a database I made the from 'FROM TABLE, jsonb_array_elements(value -> 'team') AS team(role). that seems to get it done

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.