Reputation:
I would want that at passing an object at JSON.Stringify, it checks if it has a field like "val" for stringify only that field, else been stringfied everything.
Is possible to change JSON.Stringify to stringy only a determined field?
Upvotes: 0
Views: 120
Reputation: 122956
You can use a replacer
method.
var myObj = {a:1,b:2,c:3,d:4,e:5}
,myObjStr = JSON.stringify(myObj,censor);
//=> myObjStr now: "{"a":1,"b":2,"c":3}"
function censor(key,val){
return !key ? val : val>3 ? undefined : val;
}
If I understood your question right, in your case you could use something like:
var myObj = {a:{val:1},b:{val:2},c:3,d:null,e:'noval'}
,myObjStr = JSON.stringify(
myObj,
function(key,val){
return !key
? val
: val && val.val
? JSON.stringify(val)
: undefined;
});
//=> myObjStr: {"a":"{\"val\":1}","b":"{\"val\":2}"}
Upvotes: 0
Reputation: 40512
It's quite simple:
function my_json_stringify(obj) {
return JSON.stringify("val" in obj ? obj.val : obj);
}
console.log(my_json_stringify({ a: 1, b: 2})); // => {"a":1,"b":2}
console.log(my_json_stringify({ val: { a : 3, b: 4 }, other: 5}));
// => {"a":3,"b":4}
You generally must not modify system functions. It's very bad idea. But if you have to do it, it can be done like that:
JSON.original_stringify = JSON.stringify;
JSON.stringify = function(obj) {
return JSON.original_stringify(obj.val ? obj.val : obj);
}
At least, it works in Firefox. But I don't know if it will work on any other JS implementation or not.
Upvotes: 0
Reputation: 16905
You need to watch out for falsy values:
function my_json_stringify(obj) {
return JSON.stringify(obj.hasOwnProperty("val") ? obj.val : obj);
}
Otherwise, it is going to provide wrong results for things like
{
val: ""
}
You may need to include some cross-browser solution for hasOwnProperty
as shown here.
Upvotes: 1