postgresql Postgres:如何扁平化嵌套的JSON数据

sshcrbum  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(143)

刚接触postgres。我尝试将这个嵌套的json数据扁平化,并遵循这个示例(Flatten nested JSON structure in PostgreSQL),但我被卡住了。到目前为止,结果似乎是时间戳和金额的叉积组合,我似乎无法解决。我试图最终得到的数据应该是这样的。
| 碎片|前缀|ID|时间戳|量|
| --|--|--|--|--|
| 0 | 0 | 12345 | 1703119840677243794 | 11111 |
| 0 | 0 | 12345 | 1703206309696691698 | 22222 |

SELECT 
   shard
   , prefix
   , id
   , field
   , value
   --, fields
FROM (
  SELECT 
        shard, prefix, id
        , json_object_keys(json_array_elements(fields)) as field
        , json_each_text(json_array_elements(fields)) as value
        --, fields
  FROM (
    SELECT
        (datasets -> 'shard')::text as shard,
        (datasets -> 'prefix')::text as prefix,
        (datasets -> 'id')::text as id,
        (datasets -> 'amounts' -> 'fields') as fields
            FROM(
                 SELECT 
                    json_array_elements(json) as datasets
                  FROM (
                    SELECT '[
              {
                "amounts": {
                  "fields": [
                    {
                      "amount": 11111,
                      "timestamp": "1703119840677243794"
                    },
                    {
                      "amount": 22222,
                      "timestamp": "1703206309696691698"
                    }
                  ]
                },
                "shard": 0,
                "prefix": 0,
                "id": 12345
              }
            ]'::json
        )d)c)b)a;

字符串
任何帮助将不胜感激。

2j4z5cfb

2j4z5cfb1#

我知道了json_extract_path是关键

SELECT 
        shard, prefix, id        
        , json_extract_path(json_array_elements(fields), 'amount') AS amount
        , json_extract_path(json_array_elements(fields), 'timestamp') AS timestamp
  FROM (
    SELECT
            (datasets -> 'shard')::text as shard,
            (datasets -> 'prefix')::text as prefix,
        (datasets -> 'id')::text as id,
        (datasets -> 'amounts' -> 'fields') as fields
            FROM(
          SELECT 
                      json_array_elements(json) as datasets
                  FROM (
                    SELECT '[
              {
                "amounts": {
                  "fields": [
                    {
                      "amount": 11111,
                      "timestamp": "1703119840677243794"
                    },
                    {
                      "amount": 22222,
                      "timestamp": "1703206309696691698"
                    }
                  ]
                },
                "shard": 0,
                "prefix": 0,
                "id": 12345
              }
            ]'::json
        )d)c)b;

字符串

相关问题