简体   繁体   中英

JSON_MERGE_PATCH with null values (in Javascript)

As written in the docs, JSON_MERGE_PATCH will remove each value that is set to null, the following example will remove the header value from my settings json field

const data = JSON.stringify({header: null, otherdata: ...})
await connection.query(UPDATE shops SET JSON_MERGE_PATCH(settings, ?), data)

However what if I want to set the value to null, If I surround the header: 'null' , with quotes, you can guess it: it enters 'null' as a string into my database.

Does anyone know if it's possible to have mysql update my json field with a null value?

From the JSON_MERGE_PATCH docs :

All members of the second object which do not have a corresponding key in the first object, and whose value is not the JSON null literal.

So the behavior you're seeing is expected. A possible solution which might fit your use-case would be the following:

UPDATE shops SET JSON_MERGE_PATCH('{header: null, other defaults...}', settings, ?)

This exploits the fact that the rule doesn't apply to the first object. In this way, the first argument specifies keys that should always be in the json document ( defaults ). There is a side effect though: Keys within settings that are null and are not specified within the provided defaults are going to be removed (unless they're within ? ).

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