【问题标题】:How to delete key inside object inside jsonb array in SQL?如何在 SQL 中删除 jsonb 数组中的对象内的键?
【发布时间】:2021-10-06 06:41:18
【问题描述】:

我的表的foods 列中有以下 json 数据:

[
  {
    "name": "Pasta",
    "price": 45.8,
    "comments": {
      "promo": true,
      "special": true
    }
  },
  {
    "name": "Risotto",
    "price": 31.4,
  },
  {
    "name": "Pizza",
    "price": 64.9,
    "comments": {
      "promo": true,
      "special": true
    }
  },
  {
    "name": "Hamburguer",
    "price": 14.9,
    "comments": {
      "combo": true
    }
  },
]

我想删除所有promo 键,看起来像这样。

[
  {
    "name": "Pasta",
    "price": 45.8,
    "comments": {
      "special": true
    }
  },
  {
    "name": "Risotto",
    "price": 31.4,
  },
  {
    "name": "Pizza",
    "price": 64.9,
    "comments": {
      "special": true
    }
  },
  {
    "name": "Hamburguer",
    "price": 14.9,
    "comments": {
      "combo": true
    }
  },
]

此数据可能没有多大意义,因为它是一个示例,用于显示我正在尝试解决的案例,但有更多数据,我需要删除某些对象中存在的键(不是全部,如示例中所示)位于 jsonb 数组中。 我怎样才能表现得最好?我使用的是 PostgreSQL 版本 12,所以最好使用 jsonb 函数。

【问题讨论】:

  • 使用适当的规范化数据模型会很容易。

标签: postgresql jsonb


【解决方案1】:

即使使用 jsonb 运算符,您也需要取消嵌套和重新聚合数据,这似乎可行:

create table receipts (
 receipt int,
 foods jsonb
);

insert into receipts values
(1, '[
  {
    "name": "Pasta",
    "price": 45.8,
    "comments": {
      "promo": true,
      "special": true
    }
  },
  {
    "name": "Risotto",
    "price": 31.4
  },
  {
    "name": "Pizza",
    "price": 64.9,
    "comments": {
      "promo": true,
      "special": true
    }
  },
  {
    "name": "Hamburguer",
    "price": 14.9,
    "comments": {
      "combo": true
    }
  }
]');
SELECT receipt, jsonb_agg(jsonb_strip_nulls(jsonb_set(element, '{"comments","promo"}', 'null')) ORDER BY ordinality) 
 FROM receipts
 JOIN LATERAL jsonb_array_elements(foods) WITH ORDINALITY AS el(element, ordinality)
   ON receipt = 1
GROUP BY receipt

.. 但它会删除所有空值(如果有)

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2021-05-12
    • 2023-03-03
    • 2015-12-24
    相关资源
    最近更新 更多