From ca178f0e7fe9683da51d0c3bc322fb2b99826311 Mon Sep 17 00:00:00 2001 From: Jay Doane Date: Fri, 7 Feb 2020 14:44:41 -0800 Subject: Expose `couch_util:decode/2` to support jiffy options It can be desirable in some cases for decoded JSON to e.g. return maps instead of the default data structure, which is not currently possible. This exposes a new function `couch_util:decode/2`, the second parameter being a list of options passed to `jiffy:decode/2`. --- src/couch/src/couch_util.erl | 7 +++++-- src/couch/test/eunit/couch_util_tests.erl | 7 +++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/couch/src/couch_util.erl b/src/couch/src/couch_util.erl index a785e2e44..dffb68152 100644 --- a/src/couch/src/couch_util.erl +++ b/src/couch/src/couch_util.erl @@ -21,7 +21,7 @@ -export([get_nested_json_value/2, json_user_ctx/1]). -export([proplist_apply_field/2, json_apply_field/2]). -export([to_binary/1, to_integer/1, to_list/1, url_encode/1]). --export([json_encode/1, json_decode/1]). +-export([json_encode/1, json_decode/1, json_decode/2]). -export([verify/2,simple_call/2,shutdown_sync/1]). -export([get_value/2, get_value/3]). -export([reorder_results/2]). @@ -498,8 +498,11 @@ json_encode(V) -> jiffy:encode(V, [force_utf8]). json_decode(V) -> + json_decode(V, []). + +json_decode(V, Opts) -> try - jiffy:decode(V, [dedupe_keys]) + jiffy:decode(V, [dedupe_keys | Opts]) catch error:Error -> throw({invalid_json, Error}) diff --git a/src/couch/test/eunit/couch_util_tests.erl b/src/couch/test/eunit/couch_util_tests.erl index 3e145c4f6..012c961a4 100644 --- a/src/couch/test/eunit/couch_util_tests.erl +++ b/src/couch/test/eunit/couch_util_tests.erl @@ -168,3 +168,10 @@ to_hex_test_() -> ?_assertEqual("", couch_util:to_hex(<<>>)), ?_assertEqual("010203faff", couch_util:to_hex(<<1, 2, 3, 250, 255>>)) ]. + +json_decode_test_() -> + [ + ?_assertEqual({[]}, couch_util:json_decode(<<"{}">>)), + ?_assertEqual({[]}, couch_util:json_decode(<<"{}">>, [])), + ?_assertEqual(#{}, couch_util:json_decode(<<"{}">>, [return_maps])) + ]. -- cgit v1.2.1