简体   繁体   English

JSON_MERGE_PATCH 与 null 值(在 Javascript 中)

[英]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如文档中所述,JSON_MERGE_PATCH 将删除设置为 null的每个值,以下示例将从我的设置 json 字段中删除 header 值

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.但是,如果我想将值设置为 null,如果我将header: 'null'用引号括起来,您可以猜到:它会将 'null' 作为字符串输入到我的数据库中。

Does anyone know if it's possible to have mysql update my json field with a null value?有谁知道是否有可能让 mysql 用 null 值更新我的 json 字段?

From the JSON_MERGE_PATCH docs :JSON_MERGE_PATCH 文档

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.第二个 object 的所有成员,在第一个object 中没有对应的键,并且其值不是 JSON Z37BZA6259CC0489DFF20 字面量。

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.这利用了该规则不适用于第一个object 的事实。 In this way, the first argument specifies keys that should always be in the json document ( defaults ).这样,第一个参数指定应该始终在 json 文档中的键(默认值)。 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 ? ).但是有一个副作用: settings中的键是 null 并且未在提供的默认值中指定将被删除(除非它们在?内)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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