简体   繁体   English

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

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

I have tried to unnest the JSON array with the function json_array_elements() and tried to count the elements of the array using json_array_length(field_name) not being successful.我尝试使用函数json_array_elements() JSON 数组,并尝试使用json_array_length(field_name)计算数组的元素不成功。 I am using PostgreSQL 9.4.5.我正在使用 PostgreSQL 9.4.5。

I was looking to query the result for the element "name" this is the data held on the json type array field crew :我正在寻找元素"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
        }
    ]

Your problem stems from the incorrect use of the type json[].您的问题源于对 json[] 类型的错误使用。 A json array is a single json object and its type is json, not json[]. json 数组是单个 json 对象,它的类型是 json,而不是 json[]。 Example:例子:

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
    }
]');

The function json_array_elements() works as expected:函数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)

One of the queries (or both) should work well with json[] :查询之一(或两者)应该适用于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