简体   繁体   中英

JSON.stringify filter for properties with object values is not working

Can someone please clarify the rule of filtering?

property z is not being stringified properly, see last line pls.

MDN says "if an array, specifies the set of properties included in objects in the final string."

var obj = {x:1,y:'str',z:{a:1,b:2}};
var s = JSON.stringify(obj)
"{"x":1,"y":"str","z":{"a":1,"b":2}}"
var s = JSON.stringify(obj,["x","y","z"]);
"{"x":1,"y":"str","z":{}}"   //z empty object why?

From MDN , if replacer (the second parameter of JSON.stringify) is an array it specifies the set of properties included in objects in the final string.

You set it as ["x","y","z"] in which case your resulting string has those three properties, what you may have missed is that it is applies to all properties not just those at the top level, so since you did not specify "a" and "b" in your array they where not included in the final string.

Try JSON.stringify(obj,["x","y","z", "a", "b"]); http://jsfiddle.net/mowglisanu/rhCTY/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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