Skip to content

Commit 4b1ac7c

Browse files
authored
Parse nan in JSON as NaN instead of triggering a parse error (#2712)
* Fix memory leak for has(nan) jv_array_get() used to be responsible of freeing the input array, but since b5c4c3d, it is no longer called if the key is nan. We need to free it manually to avoid leaking the array. * Parse nan in JSON as NaN instead of triggering a parse error Fixes #2021
1 parent 092fef7 commit 4b1ac7c

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

src/jv_aux.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ jv jv_has(jv t, jv k) {
215215
} else if (jv_get_kind(t) == JV_KIND_ARRAY &&
216216
jv_get_kind(k) == JV_KIND_NUMBER) {
217217
if (jvp_number_is_nan(k)) {
218+
jv_free(t);
218219
ret = jv_false();
219220
} else {
220221
jv elem = jv_array_get(t, (int)jv_number_value(k));

src/jv_parse.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,11 @@ static pfunc check_literal(struct jv_parser* p) {
490490
switch (p->tokenbuf[0]) {
491491
case 't': pattern = "true"; plen = 4; v = jv_true(); break;
492492
case 'f': pattern = "false"; plen = 5; v = jv_false(); break;
493-
case 'n': pattern = "null"; plen = 4; v = jv_null(); break;
493+
case 'n':
494+
// if it starts with 'n', it could be a literal "nan"
495+
if (p->tokenpos != 3) {
496+
pattern = "null"; plen = 4; v = jv_null();
497+
}
494498
}
495499
if (pattern) {
496500
if (p->tokenpos != plen) return "Invalid literal";

tests/jq.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,6 +1799,18 @@ reduce .[] as $then (4 as $else | $else; . as $elif | . + $then * $elif)
17991799

18001800

18011801
# { $__loc__ } works
1802+
18021803
{ a, $__loc__, c }
18031804
{"a":[1,2,3],"b":"foo","c":{"hi":"hey"}}
18041805
{"a":[1,2,3],"__loc__":{"file":"<top-level>","line":1},"c":{"hi":"hey"}}
1806+
1807+
1808+
# nan is parsed as a valid NaN value from JSON
1809+
1810+
fromjson | isnan
1811+
"nan"
1812+
true
1813+
1814+
tojson | fromjson
1815+
{"a":nan}
1816+
{"a":null}

0 commit comments

Comments
 (0)