Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

sql - Querying an array of objects in JSONB

I have a table with a column of the data type JSONB. Each row in the column has a JSON that looks something like this:

[
  {
    "A":{
      "AA": "something",
      "AB": false
    }
  },
  {
    "B": {
      "BA":[
        {
          "BAAA": [1,2,3,4]
        },
        {
          "BABA": {
           .... 
          }
        }
      ]
    }
  }
]

Note: the JSON is a complete mess of lists and objects, and it has a total of 300 lines. Not my data but I am stuck with it. :(

I am using postgresql version 12

How would I write the following queries:

  • Return all row that has the value of AB set to false.
  • Return the values of BAAA is each row.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find the AB = false rows with a JSON Path query:

select *
from test
where data @@ '$[*].A.AB == false'

If you don't know where exactly the key AB is located, you can use:

select *
from test
where data @@ '$[*].**.AB == false'

To display all elements from the array as rows, you can use:

select id, e.*
from test
  cross join jsonb_array_elements(jsonb_path_query_first(data, '$[*].B.BA.BAAA')) with ordinality as e(item, idx)

I include a column "id" as a placeholder for the primary key column, so that the source of the array element can be determined in the output.

Online example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...