Skip to content
Advertisement

How to query Json field so the keys are the column names and the values are the column fields

PostgreSQL database name is contacts_contact and the column I’m interested in is called “fields”

‘fields’ column looks like this in my database:

And a second record:

The ‘fields’ column has fields that look like the two JSON data I shared. It is pretty much responses to a survey. Example, {u’Monthly_household_income’: {u’text’: u'< R1500′}, means that the question was “Monthly household income” and the user responded with $1500.

I want the query output to have a column per question and the replies as the fields.

It should look like this:

Advertisement

Answer

As the actual value is nested inside another key, the easiest way is to use the #>> operator:

If you don’t want to type that all the time, create a view that does this.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement