From 1979919b792910e6c75f3e28596f017d980b45ee Mon Sep 17 00:00:00 2001 From: Louis Pilfold Date: Thu, 23 May 2024 19:02:55 +0100 Subject: Decoding --- src/gleam/json.gleam | 12 ++++++------ src/gleam_json_ffi.erl | 12 +++++++++++- 2 files changed, 17 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/gleam/json.gleam b/src/gleam/json.gleam index 3c50712..9aadcda 100644 --- a/src/gleam/json.gleam +++ b/src/gleam/json.gleam @@ -1,16 +1,16 @@ -import gleam/list -import gleam/result import gleam/bit_array -import gleam/option.{type Option, None, Some} import gleam/dynamic.{type Dynamic} +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result import gleam/string_builder.{type StringBuilder} pub type Json pub type DecodeError { UnexpectedEndOfInput - UnexpectedByte(byte: String, position: Int) - UnexpectedSequence(byte: String, position: Int) + UnexpectedByte(String) + UnexpectedSequence(String) UnexpectedFormat(List(dynamic.DecodeError)) } @@ -101,7 +101,7 @@ fn decode_to_dynamic(a: BitArray) -> Result(Dynamic, DecodeError) fn decode_to_dynamic(json: BitArray) -> Result(Dynamic, DecodeError) { case bit_array.to_string(json) { Ok(string) -> decode_string(string) - Error(Nil) -> Error(UnexpectedByte("", 0)) + Error(Nil) -> Error(UnexpectedByte("")) } } diff --git a/src/gleam_json_ffi.erl b/src/gleam_json_ffi.erl index c33f87f..2bfd6c6 100644 --- a/src/gleam_json_ffi.erl +++ b/src/gleam_json_ffi.erl @@ -6,7 +6,17 @@ ]). decode(Json) -> - thoas:decode(Json). + try + {ok, json:decode(Json)} + catch + error:unexpected_end -> {error, unexpected_end_of_input}; + error:{invalid_byte, Byte} -> {error, {unexpected_byte, hex(Byte)}}; + error:{unexpected_sequence, Byte} -> {error, {unexpected_sequence, Byte}} + end. + +hex(I) -> + H = list_to_binary(integer_to_list(I, 16)), + <<"0x"/utf8, H/binary>>. json_to_iodata(Json) -> Json. -- cgit v1.2.3