今天,在查BUG时,发现有一段JSON,里面的key 是 "" 空字符啊,导致插入我mongodb时,报错zero-length keys are not allowed, did you use $ with double quotes。
就郁闷了,json 可以这样的吗?如下:
{
"": 12221,
"key1": "valus"
}
有什么办法可以检查到这样的JSON数据,?或PHP对JSON字符串encode,decode时能够发现这样的错。
今天,在查BUG时,发现有一段JSON,里面的key 是 "" 空字符啊,导致插入我mongodb时,报错zero-length keys are not allowed, did you use $ with double quotes。
就郁闷了,json 可以这样的吗?如下:
{
"": 12221,
"key1": "valus"
}
有什么办法可以检查到这样的JSON数据,?或PHP对JSON字符串encode,decode时能够发现这样的错。
可以的
var obj = {"": 123,b:2}
var s = JSON.stringify(obj)
console.log(s)
"{"":123,"b":2}"
如果你的对象深度只有一层,那这样:
var a = {
'': 12221,
'key': 'value'
}
Object.keys(a).filter(x => {if (x === '') delete a[x]})
如果你的对象深度有多层,那这样:
var a = {
'': 12221,
'key': {
'': 121,
'key': 'value'
}
}
function foo (obj) {
Object.keys(obj).filter(x => {
if (x === '') delete obj[x]
else if (obj[x] !== null && typeof obj[x] === 'object') foo(obj[x])
})
}
foo(a)
写了个方法,你可以通过下面方式判断JSON数据是否含有空key。