简体   繁体   中英

how to add more key/value item into a json field in psql/postgres

I have a column named SALE in a table named HOUSE which contains below JSON:

{
   "houses":[
      {
         "houseId":"house100",
         "houseLocation":"malvern",
         "attribute":{
            "colour":[
               "white",
               "grey"
            ],
            "openForInspection":{
               "fromTime":"0001",
               "toTime":"2359"
            }
         },
         "priceRange":null
      }
   ]
}

I need to replace "priceRange":null with {"fromAmount": "100","toAmount": "1000"}

{
   "houses":[
      {
         "houseId":"house100",
         "houseLocation":"malvern",
         "attribute":{
            "colour":[
               "white",
               "grey"
            ],
            "openForInspection":{
               "fromTime":"0001",
               "toTime":"2359"
            }
         },
         "priceRange":{
            "fromAmount":"100",
            "toAmount":"1000"
         }
      }
   ]
}

I tried many different queries but was unable to get the desired results

You can use jsonb_array_elements :

select jsonb_build_object('houses', 
  (select array_agg(case when (v.value -> 'priceRange')::text = 'null' 
      then v.value::jsonb || '{"priceRange":{"fromAmount": "100","toAmount": "1000"}}'::jsonb 
      else v.value::jsonb end) 
  from json_array_elements(h.sale -> 'houses') v)) 
from house h

See fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM