繁体   English   中英

查询 JSON[] 字段数组类型内的数组元素

[英]Query for array elements inside JSON[] field array type

我尝试使用函数json_array_elements() JSON 数组,并尝试使用json_array_length(field_name)计算数组的元素不成功。 我正在使用 PostgreSQL 9.4.5。

我正在寻找元素"name"的查询结果,这是 json 类型数组字段crew中保存的数据:

    [
        {
            "workHours": "9",
            "workers": "50",
            "checker_rate": 100,
            "rate": 150,
            "name": "Ramona",
            "last": null,
            "boxRate": 2,
            "checkTraining": false,
            "editing": true,
            "ix": 0,
            "breakPay": 3.0833333333333335,
            "trainingPay": 0
        },
        {
            "workHours": "4",
            "workers": "50",
            "checker_rate": 120,
            "rate": 160,
            "name": "Ramon",
            "last": "Rosas",
            "boxRate": 2,
            "checkTraining": false,
            "editing": false,
            "id": 1,
            "breakPay": 1.5416666666666667,
            "trainingPay": 0
        }
    ]

您的问题源于对 json[] 类型的错误使用。 json 数组是单个 json 对象,它的类型是 json,而不是 json[]。 例子:

create table test (id int, crew json);
insert into test values
(1, '
[
    {
        "workHours": "9",
        "workers": "50",
        "checker_rate": 100,
        "rate": 150,
        "name": "Ramona",
        "last": null,
        "boxRate": 2,
        "checkTraining": false,
        "editing": true,
        "ix": 0,
        "breakPay": 3.0833333333333335,
        "trainingPay": 0
    },
    {
        "workHours": "4",
        "workers": "50",
        "checker_rate": 120,
        "rate": 160,
        "name": "Ramon",
        "last": "Rosas",
        "boxRate": 2,
        "checkTraining": false,
        "editing": false,
        "id": 1,
        "breakPay": 1.5416666666666667,
        "trainingPay": 0
    }
]');

函数json_array_elements()按预期工作:

select id, elem->'name' as name
from test
cross join json_array_elements(crew) elem;

 id |   name   
----+----------
  1 | "Ramona"
  1 | "Ramon"
(2 rows)

查询之一(或两者)应该适用于json[]

select id, elem->'name' as name
from test
cross join json_array_elements(crew[1]) elem;

select id, elem->'name' as name
from test
cross join unnest(crew)
cross join json_array_elements(unnest) elem;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM