From 093baaf515412da13acf98862ff9aa3074e28194 Mon Sep 17 00:00:00 2001 From: alisdair sullivan Date: Wed, 14 Dec 2011 21:32:17 -0800 Subject: [PATCH] add documentation for is_json --- README.markdown | 22 ++++++++++++++++++++++ src/jsx_verify.erl | 12 +++++++----- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/README.markdown b/README.markdown index 90ea058..a87eecf 100644 --- a/README.markdown +++ b/README.markdown @@ -103,6 +103,28 @@ if the option `escape_forward_slash` is enabled, `$/` is escaped. this is not no see the note below about streaming mode for details of `explicit_end` +**verifying json texts** + +returns true if input is a valid JSON text or erlang term that represents a JSON text, false if not. note that if you want to recognize naked (unwrapped) terms, you must specify a parser to use + +`is_json(MaybeJSON)` -> `Term` + +`is_json(MaybeJSON, Opts)` -> `Term` + +types: + +* `MaybeJSON` = `any()` +* `Term` = `true` | `false` | `{incomplete, Fun}` +* `Opts` = `[]` | `[Opt]` +* `Opt` = + - `{parser, Parser}` + * `Parser` = `jsx:decoder()` | `jsx:encoder()` + - `loose_unicode` + - `explicit_end` + +see `json_to_term` and `term_to_json` for details of options + + **streaming mode** this implementation is interruptable and reentrant and may be used to incrementally parse json texts. it's greedy and will exhaust input, returning when the stream buffer is empty. if the json text is so far valid, but incomplete (or if the option `explicit_end` has been selected), `{incomplete, Fun}` will be returned. `Fun/1` may be called with additional input (or the atom `end_stream` to force the end of parsing) diff --git a/src/jsx_verify.erl b/src/jsx_verify.erl index c8f66bb..36fdba9 100644 --- a/src/jsx_verify.erl +++ b/src/jsx_verify.erl @@ -38,10 +38,7 @@ is_json(Source, Opts) when (is_binary(Source) andalso is_list(Opts)) orelse (is_list(Source) andalso is_list(Opts)) -> - try case (gen_json:parser(?MODULE, Opts, jsx_utils:extract_opts(Opts)))(Source) of - {incomplete, _} -> false - ; true -> true - end + try (gen_json:parser(?MODULE, Opts, jsx_utils:extract_opts(Opts)))(Source) catch error:badarg -> false end. @@ -130,7 +127,7 @@ true_test_() -> false_test_() -> [ - {"unbalanced list", ?_assert(is_json(<<"[[[]]">>, []) =:= false)}, + {"unbalanced list", ?_assert(is_json(<<"[]]">>, []) =:= false)}, {"trailing comma", ?_assert(is_json(<<"[ true, false, null, ]">>, []) =:= false) }, @@ -142,6 +139,11 @@ false_test_() -> [{repeated_keys, false}]) =:= false) } ]. + +incomplete_test_() -> + [ + {"incomplete test", ?_assertMatch({incomplete, _}, is_json(<<"[">>, []))} + ]. -endif. \ No newline at end of file