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?
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?
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.
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.
obj.val ? ... will be false for a variety of defined values (false, null, 0, ''), which is probably not what the OP wants. Better to use 'val' in objYou 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}"}
replacer method with such a simplistic implementation. You would need to keep around some global state to make it work!myObj has an attribute called val and the case where it does not. (I made an error with the mention of global state, the docs aren't entirely clear about the workings, which is why I made an invalid assumption). Anyway, the censor function needs to be implemented like this: if(key === "" && value.hasOwnProperty("val")) { return value.val; } return value; --- censor gets called on the each attribute of the result of censor("", myObj") which leads to the above implementation.