aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLouis Pilfold <louis@lpil.uk>2022-02-05 09:37:37 +0000
committerLouis Pilfold <louis@lpil.uk>2022-02-05 09:37:37 +0000
commit6821a758373686042096a3b54f39743532c32aaa (patch)
tree35993985463cd39b62807e34d8a59f39c276a87d /src
parentce5c3bbbd7f4ed811f9bbaadce05165fe483c4f6 (diff)
downloadgleam_json-6821a758373686042096a3b54f39743532c32aaa.tar.gz
gleam_json-6821a758373686042096a3b54f39743532c32aaa.zip
decode_bits
Diffstat (limited to 'src')
-rw-r--r--src/gleam/json.gleam34
1 files changed, 31 insertions, 3 deletions
diff --git a/src/gleam/json.gleam b/src/gleam/json.gleam
index b94a1d4..b19c121 100644
--- a/src/gleam/json.gleam
+++ b/src/gleam/json.gleam
@@ -1,6 +1,7 @@
import gleam/map
import gleam/list
import gleam/result
+import gleam/bit_string
import gleam/option.{None, Option, Some}
import gleam/dynamic.{Dynamic}
import gleam/string_builder.{StringBuilder}
@@ -38,13 +39,40 @@ pub fn decode(
from json: String,
using decoder: dynamic.Decoder(t),
) -> Result(t, DecodeError) {
+ let bits = bit_string.from_string(json)
+ decode_bits(bits, decoder)
+}
+
+/// Decode a JSON bit string into dynamically typed data which can be decoded
+/// into typed data with the `gleam/dynamic` module.
+///
+/// ## Examples
+///
+/// ```gleam
+/// > decode_bits(<<"[1,2,3]">>, dynamic.list(of: dynamic.int))
+/// Ok([1, 2, 3])
+/// ```
+///
+/// ```gleam
+/// > decode_bits(<<"[">>, into: dynamic.list(of: dynamic.int))
+/// Error(UnexpectedEndOfInput)
+/// ```
+///
+/// ```gleam
+/// > decode_bits("<<1">>, into: dynamic.string)
+/// Error(UnexpectedFormat([dynamic.DecodeError("String", "Int", [])]))
+/// ```
+///
+pub fn decode_bits(
+ from json: BitString,
+ using decoder: dynamic.Decoder(t),
+) -> Result(t, DecodeError) {
try dynamic_value = decode_to_dynamic(json)
- dynamic_value
- |> decoder
+ decoder(dynamic_value)
|> result.map_error(UnexpectedFormat)
}
-external fn decode_to_dynamic(String) -> Result(Dynamic, DecodeError) =
+external fn decode_to_dynamic(BitString) -> Result(Dynamic, DecodeError) =
"gleam_json_ffi" "decode"
/// Convert a JSON value into a string.