![](/img/trans.png)
[英]How to query inside a postgres db having one column as json value
[英]How to query inside a column containg JSON array in postgres db
我在 postgres 数据库中有一张桌子。 在该表中,我有一列包含 JSON 数组
{
"DeviceId": "12355",
"Message": {
"Test1": [{"Name": "1"}, {"Result": "Pass"}],
"Test2":[{"Name": "2"}, {"Result": "Fail"}],
"Test3": [{"Name": "3"}, {"Result": "Pass"}],
}
}
我需要在里面查询,我希望我的 output 采用以下格式。
DeviceID Name Result
"12355" "1" "Pass"
"12355" "2" "Fail"
"12355" "3" "Pass"
以下是我尝试过的查询
select DeviceId, Message -> 'Name' as name, Message -> 'Result' as Result from table
结果并不如预期
我是 postgres DB 的新手,任何人都可以帮助我。 提前致谢
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
您可以使用json_each()
将Message
中的所有数据提取到每个元素的一行中。 之后,您可以访问数组元素。
但是,您的结构似乎设计得不是很好。 代替
"Test1" : [{"Name": "1"}, {"Result": "Pass"}]
你应该想到
"Test1" : {"Name": "1", "Result": "Pass"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.