Search code examples
sqljsonpostgresqlregexp-replace

postgresql: automated extracting strings from text


I've the following table in a postgresl database

        id  | species                                                                           
        ----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
          1 |[{"id":1,"animalName":"Lupo appennico","animalCode":"LUPO"},{"id":2,"animalName":"Orso bruno marsicano","animalCode":"ORSO"},{"id":3,"animalName":"Volpe","animalCode":"VOLPE"}]
        ----+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    
          2 |[{"id":1,"animalName":"Cinghiale","animalCode":"CINGHIALE"},{"id":2,"animalName":"Orso bruno marsicano","animalCode":"ORSO"},{"id":3,"animalName":"Cervo","animalCode":"CERVO"}]|

I would like to extract only values after '"animalName":' and put them in a new field.

        id  | new_field                                  |
        ----+--------------------------------------------+
          1 |Lupo appennico, Orso bruno marsicano,Volpe  |
        ----+--------------------------------------------+
          2 |Cinghiale, Orso bruno marsicano, Cervo      |

Unfortunately the field is a text type (not json or array). I've tried with regexp without success.


Solution

  • Your column is not of a json datatype, but it seems to contain valid json. If so, you can cast it and use json functions on it:

    select id, string_agg(j ->> 'animalName', ', ') new_field
    from mytable t
    cross join lateral jsonb_array_elements(t.species::jsonb) j(obj)
    group by id
    order by id
    

    Demo on DB Fiddle:

    id | new_field                                  
    -: | :------------------------------------------
     1 | Lupo appennico, Orso bruno marsicano, Volpe
     2 | Cinghiale, Orso bruno marsicano, Cervo