Skip to content

Commit 0b2fbf6

Browse files
committed
Add dict function
1 parent fdc7e57 commit 0b2fbf6

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/gleam/json.gleam

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import gleam/bit_array
2+
import gleam/dict.{type Dict}
23
import gleam/dynamic.{type Dynamic}
34
import gleam/dynamic/decode
45
import gleam/list
@@ -353,3 +354,21 @@ pub fn preprocessed_array(from: List(Json)) -> Json {
353354
@external(erlang, "gleam_json_ffi", "array")
354355
@external(javascript, "../gleam_json_ffi.mjs", "array")
355356
fn do_preprocessed_array(from from: List(Json)) -> Json
357+
358+
/// Encode a Dict into a JSON object using the supplied functions to encode
359+
/// the keys and the values respectively.
360+
///
361+
/// ## Examples
362+
///
363+
/// ```gleam
364+
/// > to_string(dict(dict.from_list([ #(3, 3.0), #(4, 4.0)]), int.to_string, float)
365+
/// "{\"3\": 3.0, \"4\": 4.0}"
366+
/// ```
367+
///
368+
pub fn dict(
369+
dict: Dict(k, v),
370+
keys: fn(k) -> String,
371+
values: fn(v) -> Json,
372+
) -> Json {
373+
object(dict.fold(dict, [], fn(acc, k, v) { [#(keys(k), values(v)), ..acc] }))
374+
}

test/gleam_json_test.gleam

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
import gleam/dict
12
import gleam/dynamic
23
import gleam/dynamic/decode
4+
import gleam/int
35
import gleam/json.{type Json}
46
import gleam/option.{None, Some}
57
import gleam/string
@@ -180,6 +182,11 @@ pub fn encode_bool_false_test() {
180182
|> should_encode("false")
181183
}
182184

185+
pub fn encode_dict_test() {
186+
json.dict(dict.from_list([#(3, 3.0)]), int.to_string, json.float)
187+
|> should_encode("{\"3\":3.0}")
188+
}
189+
183190
fn should_encode(data: Json, expected: String) {
184191
data
185192
|> json.to_string()

0 commit comments

Comments
 (0)