I am working with JSON.stringify(). As per the spec, it is mentioned that replacer and space are the optional arguments in the method. I observed that, when space is given without the replacer, it is omitted, with the space argument, holding an implicit dependency on replacer without having it documented, and without any apparent reason.
var obj = {"key1":"val1","key2":"val2","key3":"val3"}
var r = JSON.stringify(obj, "test");
console.log(r)
{"key1":"val1","key2":"val2","key3":"val3"}
It works when the replacer is given or it is passed as null,
var r = JSON.stringify(obj, null,"test");
console.log(r)
{
test"key1": "val1",
test"key2": "val2",
test"key3": "val3"
}
As per the end user perspective, it is intuitive to give space without replacer. Is this a known issue or is it a limitation in stringify()?
I think in this example space is not given without the replacer:
var r = JSON.stringify(obj, "test");
"test" is perceived as a replacer and is ignored as not being a proper type (function or Array). You should pass the null as a sign of omission of replacer if you want to pass the space argument.
@vsemozhetbyt Thanks.
From the above explanation, I see that space is perceived as replacer(if it is not given by the user). So don't you think we need to handle such kind of scenarios as it acts as a limitation to stringify from users viewpoint? If no, is there any scope for documentation change (as it is not mentioned elsewhere) ?
Unfortunately, Node.js can do nothing about this. This is a stringify() spec or implementation issue if this is an issue at all (it seems to me this is an expected behavior for function signature with optional parameters). At least, you can try to post a report to the v8 tracker.
As @vsemozhetbyt pointed out, this is an ECMAScript and/or V8 issue as the JSON object comes from V8, so you will need to take any issue with it to the V8 issue tracker.
@vsemozhetbyt, @mscdex Thank you for a valuable suggestion. Having said, I will follow it.
But do you think handling such expected behavior from API (stringify) will make it more robust,less error-prone by user etc., as it is frequently used in many web application ?
Well, maybe it would be more clear if inappropriate argument types would be reported by the engine instead of just ignoring.
Most helpful comment
I think in this example space is not given without the replacer:
"test"is perceived as a replacer and is ignored as not being a proper type (function or Array). You should pass thenullas a sign of omission of replacer if you want to pass the space argument.