【问题标题】:Jsonb extract in PostgresSQL - problem with '{}'::PostgresQL 中的 Jsonb 提取 - '{}' 的问题::
【发布时间】:2020-06-12 22:16:45
【问题描述】:

我在 PostgresSQL 表中有这个 jsonb 列。

{
"{\"start\":\"14:00\",\"end\":\"14:50\"}",
"{\"start\":\"14:51\",\"end\":\"15:40\"}",
"{\"start\":\"15:41\",\"end\":\"16:30\"}",
"{\"start\":\"16:31\",\"end\":\"17:20\"}"
}

我需要提取 start 和 end 的所有值。 我希望结果是这样的

id | start1 | end1 | start2 | end2 | start3 | end3 | start4 | end4

id | start1 | end1 
id | start2 | end2 
id | start3 | end3 
id | start4 | end4

通常的 ->> 对此不起作用,我不知道该怎么做。

【问题讨论】:

  • 这不是有效的 JSON。周围的大括号({})不应该是方括号([])吗?或者,也许您在这里显示了几行数据?请澄清。
  • 您好 Fabiola 欢迎来到 SO 社区。请使用tour 并查看How to Ask。将其作为问题的模板可以极大地提高您获得成功答案的机会。在这种情况下,将您的表格描述和示例数据发布为文本 - 没有图像以及该数据的预期结果。还要发布您尝试过的内容、效果以及与您的期望有何不同。
  • 转义的双引号看起来很不对劲。这不是 JSON 的存储方式。另外:多个项目需要在一个数组内,你的对象嵌套是无效的

标签: json postgresql jsonb


【解决方案1】:

你没有说你使用的是什么版本的 Postgres,但如果它可能有:

https://www.postgresql.org/docs/12/runtime-config-compatible.html#RUNTIME-CONFIG-COMPATIBLE-VERSION

standard_conforming_strings(布尔值)

This controls whether ordinary string literals ('...') treat backslashes The presence of this parameter can also be taken as an indication that the escape string syntax (E'...') is supported. Escape string syntax (Section 4.1.2.2) should be used if an application desires backslashes to be treated as escape characters.

在这种情况下,您需要处理 JSON 中的转义:

select E'{\"start\":\"14:00\",\"end\":\"14:50\"}'::jsonb;
               jsonb                
------------------------------------
 {"end": "14:50", "start": "14:00"}
(1 row)

select E'{\"start\":\"14:00\",\"end\":\"14:50\"}'::jsonb ->> 'start';
 ?column? 
----------
 14:00


select E'[
{\"start\":\"14:00\",\"end\":\"14:50\"},
{\"start\":\"14:51\",\"end\":\"15:40\"},
{\"start\":\"15:41\",\"end\":\"16:30\"},
{\"start\":\"16:31\",\"end\":\"17:20\"}
]'::jsonb;

--------------------------------------------------------------------------------------------------------------------------------------------------
 [{"end": "14:50", "start": "14:00"}, {"end": "15:40", "start": "14:51"}, {"end": "16:30", "start": "15:41"}, {"end": "17:20", "start": "16:31"}]


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多