我在匹配表中有以下数据:
{"Id":1,"Teams":[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
{"Id":2,"Teams":[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}],"TeamRank":[1,2]}
最终我想获得一个唯一团队名称的列表。
正在关注 This Question我一直在尝试使用以下方法访问团队名称属性:
SELECT json_array_elements(match->>'Teams') FROM matches
返回
ERROR: function json_array_elements(text) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 1560
我也试过 json_array_elements(match->>'Teams'::json) 和 json_array_elements(to_json(match->>'Teams')) 无济于事。
但是下面的查询
SELECT match->>'Teams' FROM matches;
返回
"[{"Name":"TeamA","Players":[{"Name":"AAA"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"CCC"},{"Name":"DDD"}]}]"
"[{"Name":"TeamA","Players":[{"Name":"CCC"},{"Name":"BBB"}]},{"Name":"TeamB","Players":[{"Name":"AAA"},{"Name":"DDD"}]}]"
最佳答案
->>
运算符将结果作为 text
,但您希望它保持为 json
。使用 ->
为您提供 json
值。
引用:http://www.postgresql.org/docs/9.4/static/functions-json.html
我相信 json_array_elements(match->>'Teams'::json)
上的操作顺序会将 Teams
转换为 json
之前运行 ->>
。 json_array_elements((match->>'Teams')::json)
应该可以工作,但它只是 ->
的迂回版本。
to_json(match->>'Teams')
转换为 text
,然后将该文本作为 json
对象提供给您。它不会将 text
解析回 json
。
关于json - 列表中的 Postgres JSON 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510727/