Eliminate double quotes from a json field in a selective manner in PostgreSQL

杀马特。学长 韩版系。学妹 提交于 2021-01-28 06:13:29

问题


I'm a new user of a PostgreSQL database with a json field which causes me some trouble. In fact, string values have been inserted into this json filed with double quote when they are supposed to be numerical values.

I have a field named "test_json" which is composed of for example these 2 rows:

{"test_name": "Full", "parameter1": "4.219", "parameter2": 4.4137}
{"test_name": "Full", "parameter1": "3.758", "parameter2": 4.159} 

I would like the 2 lines above to be after correction in this form:

{"test_name": "Full", "parameter1": 4.219, "parameter2": 4.4137}
{"test_name": "Full", "parameter1": 3.758, "parameter2": 4.159}

I would like to correct these values without having to delete everything and I cannot correct it by hand because there are tens of thousands of “parameter1” values. Can you help me make this correction?

I would like to remove the double quotes for this parameter1 only and in case it is not numeric.

I find all the lines that have this non-numerical parameter1 with :

select *
    from t_test_result
   where jsonb_typeof (t_test_result.test_json -> ' parameter1') <> 'number'
     and t_test_result.test_json ? 'parameter1'

And I guess I have to use the update function afterwards, but I can't manage it…

Thanks!

Franck


回答1:


You can use jsonb_set() to turn change the datatype of the value of attribyte parameter1:

update t_test_result
set test_json = jsonb_set(
    test_json, 
    '{parameter1}', 
    to_jsonb((test_json ->> 'parameter1')::numeric)
)
where test_json ? 'parameter1'

Demo on DB Fiddle



来源:https://stackoverflow.com/questions/64502173/eliminate-double-quotes-from-a-json-field-in-a-selective-manner-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!