gleam-lang / cookbook

👩🏾‍🍳 How to do many things in Gleam
131 stars 4 forks source link

Add basic parsing JSON example #23

Open leejarvis opened 1 week ago

leejarvis commented 1 week ago

Hello! I'd like to contribute a basic JSON parser example to the cookbook.

Not sure how canonical the example is so would welcome feedback on that or how complex a decoding you would like to see covered.

lpil commented 1 week ago

decode/zero is likely to be promoted into the stdlib, so let's use that. It has a series of examples in its documentation. How about we port those over to here? We could have one cookbook example for each one.

https://hexdocs.pm/decode/decode/zero.html

leejarvis commented 1 week ago

Added some examples to use decode/zero — haven't used it before now so open to feedback. I couldn't get a dict parsing example to work. This for example:

  let decoder = {
    use fields <- zero.field("fields", zero.dict(zero.string, zero.int))
    zero.success(fields)
  }
  "{\"fields\": {\"a\": 1, \"b\": 2}}"
  |> json.decode(zero.run(_, decoder))
  |> should.equal(Ok(dict.from_list([#("a", 1), #("b", 2)])))

returns Error(UnexpectedFormat([DecodeError(expected: "Dict", found: "Object", path: ["fields"])]))