[英]How to query inside a column containg JSON array in postgres db
I have a table in postgres db.我在 postgres 数据库中有一张桌子。 In that table I have a column containing JSON array
在该表中,我有一列包含 JSON 数组
{
"DeviceId": "12355",
"Message": {
"Test1": [{"Name": "1"}, {"Result": "Pass"}],
"Test2":[{"Name": "2"}, {"Result": "Fail"}],
"Test3": [{"Name": "3"}, {"Result": "Pass"}],
}
}
I need to query inside this and I want my output to be in below format.我需要在里面查询,我希望我的 output 采用以下格式。
DeviceID Name Result
"12355" "1" "Pass"
"12355" "2" "Fail"
"12355" "3" "Pass"
Following is the query which I tried以下是我尝试过的查询
select DeviceId, Message -> 'Name' as name, Message -> 'Result' as Result from table
The result was not as expected结果并不如预期
I'm new to postgres DB can anyone help me in this.我是 postgres DB 的新手,任何人都可以帮助我。 Thanks in advance
提前致谢
SELECT
mydata ->> 'DeviceId' as device_id,
tests.value -> 0 ->> 'Name' as name,
tests.value -> 1 ->> 'Result' as result
FROM mytable,
json_each(mydata -> 'Message') as tests
You can extract all data from Message
into one row per element using json_each()
.您可以使用
json_each()
将Message
中的所有数据提取到每个元素的一行中。 Afterwards you can access the array elements.之后,您可以访问数组元素。
However, your structure seems not very well designed.但是,您的结构似乎设计得不是很好。 Instead of
代替
"Test1" : [{"Name": "1"}, {"Result": "Pass"}]
you should think of你应该想到
"Test1" : {"Name": "1", "Result": "Pass"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.