如何使用SQL访问json字符串内列表中的值

eulz3vhy  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(187)

我在一个名为"profile"的表中有一列,它以下面的格式存储信息:

[{"id":"X","type":"location"}],"avatar":{"id":"X","type":"Avatar"},"gender":{"id":"F","type":"Gender","value":"F"},"contacts":[{"id":"0230", "role": "teacher", "school": "XYZ"}],"lastName":"","nickname":"B","religion":{"id":"Unknown","type":"Religion"},"birthDate":"2a","ethnicity":{"id":"NotStated","type":"Ethnicity","category":"OtherEthnicGroups"},"firstName":"","nameTitle":""}

如何访问contactsroleschool的值?我尝试使用:profile->'contacts'->'role'profile->'contacts'->0->'role',但这两个都没有按预期工作。
先谢谢你。

y1aodyip

y1aodyip1#

对于一个有效的json,你可以使用函数json_to_recordset():

SELECT 
    *
FROM json_to_recordset(profile->'contacts') as j(id int, role text, school text);

如果数据类型是jsonb,则应使用jsonb函数jsonb_to_recordset()。

相关问题