簡體   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