|
| 1 | +//// # Generate JSON |
| 2 | +//// |
| 3 | +//// The gleam_json package can be used to generate JSON. It works on any |
| 4 | +//// target. |
| 5 | +//// |
| 6 | +//// ## Dependencies |
| 7 | +//// |
| 8 | +//// - https://hex.pm/packages/gleam_json |
| 9 | + |
| 10 | +import gleam/json |
| 11 | +import gleam/string |
| 12 | +import gleeunit/should |
| 13 | + |
| 14 | +pub fn main_test() { |
| 15 | + // The `gleam/json` module has a function for each different type of data in |
| 16 | + // a JSON document. e.g. `bool`, `string`, `int`, etc. |
| 17 | + // |
| 18 | + // The `preprocessed_array` function is used for arrays made from list |
| 19 | + // that already contain JSON data. |
| 20 | + // |
| 21 | + let document = |
| 22 | + json.object([ |
| 23 | + #( |
| 24 | + "bookstore", |
| 25 | + json.preprocessed_array([ |
| 26 | + json.object([ |
| 27 | + #("genre", json.string("Technology")), |
| 28 | + #("title", json.string("Introduction to JSON")), |
| 29 | + #("author", json.string("Kwame Nkrumah")), |
| 30 | + ]), |
| 31 | + json.object([ |
| 32 | + #("genre", json.string("Programming")), |
| 33 | + #("title", json.string("Learning Gleam")), |
| 34 | + #("author", json.string("Mei Wong")), |
| 35 | + ]), |
| 36 | + ]), |
| 37 | + ), |
| 38 | + ]) |
| 39 | + |
| 40 | + // The document can be converted to a string |
| 41 | + document |
| 42 | + |> json.to_string |
| 43 | + |> should.equal( |
| 44 | + " |
| 45 | +{ |
| 46 | + \"bookstore\":[ |
| 47 | + { |
| 48 | + \"genre\":\"Technology\", |
| 49 | + \"title\":\"Introduction to JSON\", |
| 50 | + \"author\":\"Kwame Nkrumah\" |
| 51 | + }, |
| 52 | + { |
| 53 | + \"genre\":\"Programming\", |
| 54 | + \"title\":\"Learning Gleam\", |
| 55 | + \"author\":\"Mei Wong\" |
| 56 | + } |
| 57 | + ] |
| 58 | +} |
| 59 | + " |
| 60 | + |> string.replace(" ", "") |
| 61 | + |> string.replace("\n", ""), |
| 62 | + ) |
| 63 | + |
| 64 | + // If you have a collection of items and you wish to map over each of them to |
| 65 | + // make JSON then you can use the `array` function rather than the |
| 66 | + // `preprocessed_array` function. |
| 67 | + let directions = ["North", "East", "South", "West"] |
| 68 | + json.object([ |
| 69 | + #( |
| 70 | + "directions", |
| 71 | + json.array(directions, fn(direction) { |
| 72 | + json.object([#("name", json.string(direction))]) |
| 73 | + }), |
| 74 | + ), |
| 75 | + ]) |
| 76 | + |> json.to_string |
| 77 | + |> should.equal( |
| 78 | + " |
| 79 | +{ |
| 80 | + \"directions\":[ |
| 81 | + {\"name\":\"North\"}, |
| 82 | + {\"name\":\"East\"}, |
| 83 | + {\"name\":\"South\"}, |
| 84 | + {\"name\":\"West\"} |
| 85 | + ] |
| 86 | +} |
| 87 | + " |
| 88 | + |> string.replace(" ", "") |
| 89 | + |> string.replace("\n", ""), |
| 90 | + ) |
| 91 | +} |
0 commit comments