我试图从一些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'

然后,我try 使用以下内容进行查询:

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

然后将如下所示的ChannelID值放入本地临时表

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

推荐答案

您需要将列数据类型从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

Json相关问答推荐

无法从MongoDB集合中检索正确的文档

无法访问id的第三级json

解析Ansible AWS ec2_security_group中的json以提取安全组ID

jq 对特定键进行过滤并将值整理到单个 csv 单元格中

在 python 中循环 JSON 数组

Spark-SQL中的from_unixtime函数未能给出正确的输出

JOLT - 如果对象内部存在键,则将对象移动到数组

如何从字符串中创建一个逗号分隔的列表,由 API 中的 JSON 对象内的编号空格分隔?

JOLT JSON 将值从一对多转换为一对一

将 colly 包输出文本添加到 golang 中的映射

提交后使用 Rails 7 结合 JSON 标签进行标记

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

Newtonsoft Json 将值 {null} 转换为类型System.Int32时出错

在 Rails 中使用 JSON 创建嵌套对象

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

将序列化表单的数据转换为 json 对象

在 HTML 数据属性上添加 JSON 是不是很糟糕?

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

jq:按属性分组和键