使用JSON.parse reviver来模糊字段 [英] Using a JSON.parse reviver to obfuscate fields
问题描述
我基本上想让某些字段为null。
如果我这样做:
var json_data = JSON.parse(j,function(key,value ){
if(key ==name){
return value;
} else {
return null;
}
});
整个json_data对象最终为空。实际上,不管我做了什么,它定义了json_object的价值。
有趣的是,这样可以预期:
var json_data = JSON.parse(j,function(key,value){
if(key ==name){
return name;
} else {
return value;
}
});
现在,属性name的值为name。
JSON有问题:
var j ='{uuid:62cfb2ec-9e43- 11e1-abf2-70cd60fffe0e,count:1,name:Marvin,date:2012-05-13T14:06:45 + 10:00
更新
我只是意识到我想做的事情的反向也是如此,所以我可以取消名字域:
var json_data = JSON.parse(j,function (key,value){
if(key ==name){
return null;
} else {
return value;
}
});
通过一些实验,键是空字符串的函数,值是顶级对象:
> JSON.parse('{hello:world}',function(k,v){console.log(arguments); return v;})
[hello,world]
[,Object]
所以你可以使用:
var json_data = JSON.parse(j,function(key,value){
if(key ==name|| key === ){
return value;
} else {
return null;
}
});
现在,由于成为一个有效的JSON密钥,要100%正确,最好使用以下方式:
var json_data;
JSON.parse(j,function(key,value){
if(key ==name){
return value;
} else if(key == ){
json_data = value;
return null;
} else {
return null;
}
});
但这可能有点偏执;)
I am attempting to abuse a reviver function with JSON.parse.
I basically want to make certain fields "null".
If I do this:
var json_data = JSON.parse(j, function(key, value) {
if (key == "name") {
return value;
} else {
return null;
}
});
The entire json_data object ends up null. In fact, no matter what I make the else, that defines the value of the json_object.
Interestingly, this works as expected:
var json_data = JSON.parse(j, function(key, value) {
if (key == "name") {
return "name";
} else {
return value;
}
});
The property "name" now has a value of "name".
JSON in question:
var j = '{"uuid":"62cfb2ec-9e43-11e1-abf2-70cd60fffe0e","count":1,"name":"Marvin","date":"2012-05-13T14:06:45+10:00"}';
Update
I just realized that the inverse of what I want to do works as well so I can nullify the name field:
var json_data = JSON.parse(j, function(key, value) {
if (key == "name") {
return null;
} else {
return value;
}
});
Through some experimentation, it looks like a final call is made to the function where the key is an empty string and the value is the top-level object:
> JSON.parse('{"hello": "world"}', function(k, v) { console.log(arguments); return v; })
["hello", "world"]
["", Object]
So you could use:
var json_data = JSON.parse(j, function(key, value) {
if (key == "name" || key === "") {
return value;
} else {
return null;
}
});
Now, since ""
does appear to be a valid JSON key, to be 100% correct it might be better to use something like:
var json_data;
JSON.parse(j, function(key, value) {
if (key == "name") {
return value;
} else if (key === "") {
json_data = value;
return null;
} else {
return null;
}
});
But that might be a little bit paranoid ;)
这篇关于使用JSON.parse reviver来模糊字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!