Collect Recursive JSON Keys In Postgres

前端 未结 3 1052
借酒劲吻你
借酒劲吻你 2020-12-03 08:59

I have JSON documents stored in Postgres under the JSON data type (Postgres 9.3) and I need to recursively collect the key names down the tree.

For example, given th

3条回答
  •  天涯浪人
    2020-12-03 09:31

    A little more concise version that you can just test with:

    WITH RECURSIVE reports (key, value) AS (
      SELECT
        NULL as key,
        '{"k1": {"k2": "v1"}, "k3": {"k4": "v2"}, "k5": "v3"}'::JSONB as value
    
    UNION ALL
    
       SELECT
        jsonb_object_keys(value)as key,
        value->jsonb_object_keys(value) as value
       FROM
        reports
       WHERE
        jsonb_typeof(value) = 'object'
    )
    
    SELECT
        *
    FROM
        reports;
    

    This will return a list that you then need to group with distinct.

提交回复
热议问题