We can access any JSON element in PostgreSQL 9.3 using the ->
and ->>
operators. Seems to me that the #>
along with #>>
only provide a shorter form of writing the JSON path. Or is there a bigger picture behind the #>
operator? Does it serve a special purpose/provide any advantage over the arrow notation? Which one is the preffered method of writing paths?
It all comes to the question: why should I use the #>
and #>>
operator over the ->
and ->>
?
The docs are a bit enigmatic about this.
Both queries below give the same result:
=> select '{"a":[1,2,3],"b":[4,5,6]}'::json#>'{a,2}';
?column?
----------
3
=> select '{"a":[1,2,3],"b":[4,5,6]}'::json->'a'->>2;
?column?
----------
3
Consider nesting.
{
"a" : {
"b" : {
"c" : 1,
"d" : 2
}
}
}
Imagine that you have a json document, and you don't know in advance how it will be nested. If you knew you needed a three level path, you could write:
SELECT '{
"a" : {
"b" : {
"c" : 1,
"d" : 2
}
}
}'::json -> 'a' -> 'b' -> 'c';
but what if you want to write a query that doesn't know that in advance? That's where the path-based operators are useful; the path can be supplied along with the document, and there's no longer any assumption about the document structure in the query.
SELECT '{
"a" : {
"b" : {
"c" : 1,
"d" : 2
}
}
}'::json #>> ARRAY['a','b','c']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With