Long story short, JSON.stringify takes optional second argument which
can be a replacer function. It is supposed to be called for each
encountered key-value during serialization. While replacer's second
argument is already serialized (so you could just return it), just in
case you are not satisfied with default serialization — the original
value is still passed in together with the whole object as a value of
JavaScript `this`.
Sadly, there is no test in the whole ECMA test suite to catch this bug.
This is quite a breaking change for code which already uses Qt-specific
workarounds, so it would be better not to cherry-pick it as a hot-fix
onto existing (released) branches.
Sample use case: serialize dates as a number of seconds since epoch.
function replacer(k, v) {
if (this[k] instanceof Date) {
return Math.floor(this[k].getTime() / 1000.0);
}
return v;
}
const str = JSON.stringify(obj, replacer);
[ChangeLog][QML][Important Behavior Changes] Set correct `this` value in
JSON.stringify replacer scope, so that the value for current key in
current object is no longer pre-stringified, and can actually be used to
implement custom object serialization logic.
Fixes: QTBUG-95324
Change-Id: I618a533e8eba7999d5416aca14f4971093a83f7a
Reviewed-by: Ulf Hermann <ulf.hermann@qt.io>
(cherry picked from commit 4c930247e6)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>