[njs] Added support for accessor properties in JSON.stringify().
Dmitry Volyntsev
xeioex at nginx.com
Thu Aug 8 11:20:11 UTC 2019
details: https://hg.nginx.org/njs/rev/239f3511397b
branches:
changeset: 1118:239f3511397b
user: Dmitry Volyntsev <xeioex at nginx.com>
date: Thu Aug 08 14:19:56 2019 +0300
description:
Added support for accessor properties in JSON.stringify().
This closes #203 issue on Github.
diffstat:
src/njs_json.c | 27 ++++++++++++++++++++++-----
src/test/njs_unit_test.c | 8 ++++++++
2 files changed, 30 insertions(+), 5 deletions(-)
diffs (62 lines):
diff -r fd09c657f97d -r 239f3511397b src/njs_json.c
--- a/src/njs_json.c Thu Aug 08 14:19:55 2019 +0300
+++ b/src/njs_json.c Thu Aug 08 14:19:56 2019 +0300
@@ -1214,7 +1214,7 @@ njs_json_stringify_iterator(njs_vm_t *vm
njs_value_t *key, *value;
njs_function_t *to_json;
njs_json_state_t *state;
- njs_object_prop_t *prop;
+ njs_object_prop_t *prop, scratch;
njs_lvlhsh_query_t lhq;
start:
@@ -1255,10 +1255,27 @@ start:
prop = lhq.value;
- if (!prop->enumerable
- || njs_is_undefined(&prop->value)
- || !njs_is_valid(&prop->value)
- || njs_is_function(&prop->value))
+ if (!prop->enumerable) {
+ break;
+ }
+
+ if (njs_is_accessor_descriptor(prop)
+ && njs_is_function(&prop->getter))
+ {
+ scratch = *prop;
+ prop = &scratch;
+
+ ret = njs_function_apply(vm, njs_function(&prop->getter),
+ &state->value, 1, &prop->value);
+
+ if (njs_slow_path(ret != NJS_OK)) {
+ return ret;
+ }
+ }
+
+ if (njs_is_undefined(&prop->value)
+ || njs_is_function(&prop->value)
+ || !njs_is_valid(&prop->value))
{
break;
}
diff -r fd09c657f97d -r 239f3511397b src/test/njs_unit_test.c
--- a/src/test/njs_unit_test.c Thu Aug 08 14:19:55 2019 +0300
+++ b/src/test/njs_unit_test.c Thu Aug 08 14:19:56 2019 +0300
@@ -12766,6 +12766,14 @@ static njs_unit_test_t njs_test[] =
{ njs_str("JSON.stringify([{a:1,b:{c:2}},1], undefined, new Date())"),
njs_str("[{\"a\":1,\"b\":{\"c\":2}},1]") },
+ { njs_str("var o = Object.defineProperty({}, 'a', { get() { return ()=> 1}, enumerable: true });"
+ "JSON.stringify(o)"),
+ njs_str("{}") },
+
+ { njs_str("var o = Object.defineProperty({}, 'a', { get: () => ({b:1, c:2}), enumerable: true });"
+ "JSON.stringify(o)"),
+ njs_str("{\"a\":{\"b\":1,\"c\":2}}") },
+
{ njs_str("JSON.stringify({toJSON:function(k){}})"),
njs_str("undefined") },
More information about the nginx-devel
mailing list