Packages

Bidirectional, error-accumulating validation and sanitization codecs for Gleam.

Current section

Files

Jump to
pedantic src pedantic@json.erl
Raw

src/pedantic@json.erl

-module(pedantic@json).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/pedantic/json.gleam").
-export([decode_json/2, encode_json/2]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/pedantic/json.gleam", 12).
?DOC(" Decodes a JSON string using the provided Codec. Accumulates errors if the JSON is valid but does not match the schema.\n").
-spec decode_json(pedantic@codec:codec(FYG), binary()) -> {ok, FYG} |
{error, pedantic@report:report()}.
decode_json(Codec, Json_string) ->
Dyn_decoder = gleam@dynamic@decode:new_primitive_decoder(
<<"Dynamic"/utf8>>,
fun(Field@0) -> {ok, Field@0} end
),
case gleam@json:parse(Json_string, Dyn_decoder) of
{ok, Dyn} ->
(erlang:element(3, erlang:element(3, Codec)))(Dyn);
{error, Json_err} ->
Msg = case Json_err of
unexpected_end_of_input ->
<<"Unexpected end of input"/utf8>>;
{unexpected_byte, B} ->
<<"Unexpected byte: "/utf8, B/binary>>;
{unexpected_sequence, S} ->
<<"Unexpected sequence: "/utf8, S/binary>>;
{unable_to_decode, _} ->
<<"Unable to decode"/utf8>>
end,
Err = pedantic@report:make_error(
[],
{invalid_format, Msg},
gleam_stdlib:identity(Json_string)
),
{error, {report, [Err], []}}
end.
-file("src/pedantic/json.gleam", 35).
?DOC(" Encodes a value into a JSON string using the provided Codec.\n").
-spec encode_json(pedantic@codec:codec(FYK), FYK) -> binary().
encode_json(Codec, Val) ->
Dyn = (erlang:element(3, erlang:element(4, Codec)))(Val),
pedantic_ffi:encode_json_string(Dyn).