From 5dbb9b5f24dc603ebf7c1196e2483ecf0b49079c Mon Sep 17 00:00:00 2001 From: Dmitry Kolesnikov Date: Fri, 24 May 2019 22:54:36 +0300 Subject: [PATCH] Support custom newline symbol(s) for format option --- .gitignore | 4 ++++ README.md | 8 ++++++-- src/jsx_to_json.erl | 14 ++++++++++++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 4a8eee6..344bb12 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,7 @@ erl_crash.dump .DS_Store doc .rebar +*.sublime-* +rebar3 +_build/ + diff --git a/README.md b/README.md index 40fa989..1659553 100644 --- a/README.md +++ b/README.md @@ -572,8 +572,9 @@ format(JSON) -> JSON format(JSON, Opts) -> JSON JSON = json_text() - Opts = [option() | space | {space, N} | indent | {indent, N}] - N = pos_integer() + Opts = [option() | space | {space, N} | indent | {indent, N} | {newline, LF}] + N = pos_integer() + LF = binary() ``` `format` parses a json text (a `utf8` encoded binary) and produces a new json @@ -586,6 +587,9 @@ the option `{indent, N}` inserts a newline and `N` spaces for each level of indentation in your json output. note that this overrides spaces inserted after a comma. `indent` is an alias for `{indent, 1}`. the default is `{indent, 0}` +the option `{newline, LF}` defines a custom newline symbol(s). +the default is `{newline, <<$\n>>}` + raises a `badarg` error exception if input is not valid json diff --git a/src/jsx_to_json.erl b/src/jsx_to_json.erl index c2d5832..fb14df3 100644 --- a/src/jsx_to_json.erl +++ b/src/jsx_to_json.erl @@ -32,7 +32,8 @@ -record(config, { space = 0, indent = 0, - depth = 0 + depth = 0, + newline = <<$\n>> }). -type config() :: list(). @@ -62,6 +63,8 @@ parse_config([{indent, Val}|Rest], Config) when is_integer(Val), Val > 0 -> parse_config(Rest, Config#config{indent = Val}); parse_config([indent|Rest], Config) -> parse_config(Rest, Config#config{indent = 1}); +parse_config([{newline, Val}|Rest], Config) when is_binary(Val) -> + parse_config(Rest, Config#config{newline = Val}); parse_config([{K, _}|Rest] = Options, Config) -> case lists:member(K, jsx_config:valid_flags()) of true -> parse_config(Rest, Config) @@ -128,7 +131,7 @@ space(Config) -> indent(Config) -> case Config#config.indent of 0 -> <<>> - ; X when X > 0 -> <> + ; X when X > 0 -> <<(Config#config.newline)/binary, (binary:copy(?space, X * Config#config.depth))/binary>> end. @@ -383,6 +386,13 @@ format_test_() -> [{Title, ?_assertEqual(Min, jsx:minify(Pretty))} || {Title, Min, Pretty} <- Cases] ++ [{Title, ?_assertEqual(Pretty, jsx:prettify(Min))} || {Title, Min, Pretty} <- Cases]. +custom_newline_test_() -> + [ + {"single key object", ?_assert( + jsx:format(<<"{\"k\":\"v\"}">>, [space, {indent, 2}, {newline, <<$\r>>}]) + =:= <<"{\r \"k\": \"v\"\r}">>) + } + ]. handle_event_test_() -> Data = jsx:test_cases() ++ jsx:special_test_cases(),