Over the past few weeks I've been having to deal with nested JSON columns in Postgres. It was turning into me just throwing queries at it until something stuck. Well, as it would turn out, it's actually very simple! I just needed to take the time to sit down and learn about a few operators and what they're actually doing.
With that being said, here is a condensed version of some things I learned that helped me navigate through JSON columns in Postgres.
First, let's create a very basic table containing a json column
createtablesample_table(json_datajsonb);
Now, let's seed this table with some data about a few different vehicles
Now that we have our data, let's go over some of the basics.
If you've read my post about the Bacon Cannon, then you know that I am a firm believer that unique operators deserve unique names. So, as I cover some unique operators, I will be throwing in their nicknames, at no extra charge to you!
Now, as I said before, this isn't giving us text values. These quotations are an indicator that ->is returning JSON. In order to grab the text value we need to use the ->>(Double Stabby) operator. This is equivalent to adding ::text afterwards, typecasting it to a text.
I hope this helps clear up any confusion you might have had about querying nested JSON objects in Postgres.
If you want to learn more about these operators or if you want to see what else you can do, here is a link to the docs for JSON functions in Postgres.
Photo by: Karen Ciocca