I have tried to Unnest the JSON array with the function json_array_elements(), and tried to count the element of the array using json_array_length(field_name) not being successful I am using PostgreSQL 9.4.5.
I was looking to query the result for the element 'name' this is the data hold on the json type array field crew | 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
}
]
答案 0 :(得分:1)
你的问题源于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, json_array_elements(crew) elem;
id | name
----+----------
1 | "Ramona"
1 | "Ramon"
(2 rows)
其中一个查询(或两者)应该适用于json[]
:
select id, elem->'name' as name
from test, json_array_elements(crew[1]) elem;
select id, elem->'name' as name
from test, unnest(crew), json_array_elements(unnest) elem;