postgresql 从Postgres表中的JSON提取值

d6kp6zgx  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(169)

我试图从一些JSON中提取值,并在这方面陷入困境。
我的JSON如下:

{
  "SerialNumber":"940860",
  "ChannelIDs":[17,13,11,12,14],
  "BeginningDate":"2023-05-20T11:53:39",
  "EndDate":"2023-05-22T09:04:04"
}

字符串
我将其保存为一个名为spj2.json的文件,然后运行以下命令加载该文件,如下所示:

CREATE TABLE tmp (c TEXT);

copy tmp from 'C:\temp\spj2.json'


然后我尝试使用以下命令查询:

select
    c ->> 'SerialNumber' as SerialNumber,
    c ->> 'BeginningDate' as BeginningDate,
    c ->> 'EndDate' as EndDate
from tmp;


但得到以下错误消息

[2023-11-07 10:54:05] [22P02] ERROR: invalid input syntax for type json
[2023-11-07 10:54:05] Detail: The input string ended unexpectedly.
[2023-11-07 10:54:05] Where: JSON data, line 1: {
[2023-11-07 10:54:05] COPY tmp, line 1, column c: "{"


我想做的是从JSON中提取值,如下所示:

SerialNumber    BeginningDate                EndDate
940860          2023-05-20T11:53:39          2023-05-22T09:04:04


然后将如下所示的URL ID值添加到本地临时表中

ID       ChannelID 
1        11
2        12 
3        13 
4        14
5        17

pxq42qpu

pxq42qpu1#

您需要将列数据类型从text转换为json

select
    c::json ->> 'SerialNumber' as SerialNumber,
    c::json ->> 'BeginningDate' as BeginningDate,
    c::json ->> 'EndDate' as EndDate
from tmp;

字符串
测试结果:

serialnumber    beginningdate        enddate
940860          2023-05-20T11:53:39  2023-05-22T09:04:04


第二个查询可以使用json_array_elements完成:

select row_number() over (order by ChannelID::text::int ) as ID, ChannelID
from tmp
CROSS JOIN LATERAL json_array_elements(c::json -> 'ChannelIDs') as ChannelID


测试结果:

id  channelid
1   11
2   12
3   13
4   14
5   17


Demo here

相关问题