From 9a14c92bf06b47fc3888130098e21d53d84ea682 Mon Sep 17 00:00:00 2001 From: Olivier Cinquin Date: Thu, 4 Feb 2016 21:04:22 -0800 Subject: [PATCH] Enhance the "add" operator so that, when applied to objects, if two fields with the same name have a numerical value the corresponding field of the result object is set to the sum of the field values. (The previous behavior was for one of the values to just be discarded.) --- src/jv.c | 12 +++++++++++- tests/jq.test | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/jv.c b/src/jv.c index e064baf572..aabda30b7f 100644 --- a/src/jv.c +++ b/src/jv.c @@ -1134,7 +1134,17 @@ int jv_object_length(jv object) { jv jv_object_merge(jv a, jv b) { assert(jv_get_kind(a) == JV_KIND_OBJECT); jv_object_foreach(b, k, v) { - a = jv_object_set(a, k, v); + jv v_a = jv_object_get(jv_copy(a), jv_copy(k)); + + if (jv_get_kind(v) == JV_KIND_NUMBER && + jv_is_valid(v_a) && + jv_get_kind(v_a) == JV_KIND_NUMBER) { + a = jv_object_set(a, k, + jv_number(jv_number_value(v_a) + jv_number_value(v))); + } else { + a = jv_object_set(a, k, v); + } + jv_free(v_a); } jv_free(b); return a; diff --git a/tests/jq.test b/tests/jq.test index 630c344d0f..dc816e2b0d 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -552,7 +552,7 @@ null map(add) [[], [1,2,3], ["a","b","c"], [[3],[4,5],[6]], [{"a":1}, {"b":2}, {"a":3}]] -[null, 6, "abc", [3,4,5,6], {"a":3, "b": 2}] +[null, 6, "abc", [3,4,5,6], {"a":4, "b": 2}] map_values(.+1) [0,1,2]