Skip to content
Advertisement

How to process json data and put it into arrays in postgresql

I have a postgresql table with two columns. name VARCHAR(255) and notes JSON. A sample dataset might look like this:

Now I want to do two things.

  1. put the list from the json at ‘link_to’ into another column called referrals_to (which must be of array VARCHAR type then). From my example:

    name notes referrals_to
    ‘anna’ {‘link_to’: [‘bob’]} [‘bob’]
    ‘bob’ {‘link_to’: [‘anna’, ‘claudia’]} [‘anna’, ‘claudia’]
    ‘claudia’ {‘link_to’: []} []
  2. create another column called referrals_from, where I want to store all names from which a name was referred. In my example:

    name notes referrals_from
    ‘anna’ {‘link_to’: [‘bob’]} [‘bob’]
    ‘bob’ {‘link_to’: [‘anna’, ‘claudia’]} [‘anna’]
    ‘claudia’ {‘link_to’: []} [‘bob’]

How do I do this using postgresql queries? I could easily do it using python, but this would be slower than using postgresql directly, I guess.

Advertisement

Answer

The referrals_to column can be done using the -> operator to extract the array. For the referrals_from column I would use a scalar sub-select to collect all referring names into a single column (a JSON array)

The ? operator tests if a JSON array contains a specific string. In this case it tests if the link_to array contains the name from the outer query.

Online Example

Assuming name is unique in your table you can use that query to update the new columns in the table:

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