[英]Get key and value from unstructured JSON data
I have the following table with some data:我有一些数据下表:
Table:桌子:
create table tbl_jsontest
(
id int,
jdata json
);
Records:记录:
insert into tbl_jsontest values(1,'{"Id":1,"Name":"Jack"}');
insert into tbl_jsontest values(1,'[{"Id":2,"Name":"Mak"},{"Name":"Aez","Address":"ZX"}]');
insert into tbl_jsontest values(1,'[{"Id":5,"Name":"Lee"}]');
Query:询问:
SELECT json_data.key AS key1,
json_data.value AS value1
FROM tbl_jsontest,
json_each_text(tbl_jsontest.jdata) AS json_data;
Getting an error:收到错误:
ERROR: cannot deconstruct an array as an object
错误:无法将数组解构为 object
The json_each_text function takes a json object as input and does not work with array. json_each_text function 将 json object 作为输入并且不适用于数组。
Documentation https://www.postgresql.org/docs/current/functions-json.html文档https://www.postgresql.org/docs/current/functions-json.html
json_each_text ( json ) → setof record ( key text, value text )
Expands the top-level JSON object into a set of key/value pairs. json_each_text ( json ) → setof record ( key text, value text )
将顶层 JSON object 扩展为一组键/值对。 The returned values will be of type text.返回的值将是文本类型。
You can first expand the arrays with json_array_elements
and then expand the objects您可以先用 json_array_elements 展开
json_array_elements
然后展开对象
Also you should reformat jdata to same format您还应该将 jdata 重新格式化为相同的格式
Records:记录:
insert into tbl_jsontest values(1,'[{"Id":1,"Name":"Jack"}]');
insert into tbl_jsontest values(1,'[{"Id":2,"Name":"Mak"},{"Name":"Aez","Address":"ZX"}]');
insert into tbl_jsontest values(1,'[{"Id":5,"Name":"Lee"}]');
Query:询问:
select t.id, key, value
from (SELECT id, json_array_elements(tbl_jsontest.jdata) d
FROM tbl_jsontest) t,
json_each_text(t.d);
Results:结果:
+--+-------+-----+
|id|key |value|
+--+-------+-----+
|1 |Id |2 |
|1 |Name |Mak |
|1 |Name |Aez |
|1 |Address|ZX |
|1 |Id |5 |
|1 |Name |Lee |
|1 |Id |1 |
|1 |Name |Jack |
+--+-------+-----+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.