midas-framework / midas

A framework for Gleam, Midas makes shiny things.
https://hex.pm/packages/midas
169 stars 4 forks source link

JSON library #11

Open CrowdHailer opened 4 years ago

CrowdHailer commented 4 years ago

Jiffy makes use of NIF's jsone is simpler, jsx handles streaming etc

CrowdHailer commented 4 years ago

I will consider this done enough for milestone 0.2.0 the readme in gleam_jsone is enough information for now. However a general input parsing would be good, something that worked equally on querys form data and json.

CrowdHailer commented 4 years ago

For building arbitrary JSON data, a functional interface is probably best. e.g.

import jason.{object, string, boolean}
let body = jason.encode(
    object(
      [
        tuple("id_token", string(id_token)),
        tuple(
          "userinfo",
          object(
            [
              tuple("sub", string(email_address)),
              tuple("email", string(email_address)),
              tuple("email_verified", boolean(True)),
            ],
          ),
        ),
      ],
    ),
  )

This is extensible with your own types, for example dates etc. Also for simplicity I think the return value from object should be the same as the return value from a decode function.

Certainly the above is similar in complexity to building with types. but it is cheaper, less intermediate data structures and with the benefit of extensibility.

  JsonObject(
    [
      tuple("id_token", JsonString(id_token)),
      tuple(
        "userinfo",
        JsonObject(
          [
            tuple("sub", JsonString(email_address)),
            tuple("email", JsonString(email_address)),
            tuple("email_verified", JsonBool(True)),
          ],
        ),
      ),
    ],
  ),

And is conceptually simpler to building your own dynamic data structures.

  let body = jason.encode(
    dynamic.from(
      map.from_list(
        [
          tuple("id_token", dynamic.from(id_token)),
          tuple(
            "userinfo",
            dynamic.from(
              map.from_list(
                [
                  tuple("sub", dynamic.from(email_address)),
                  tuple("email", dynamic.from(email_address)),
                  tuple("email_verified", dynamic.from(True)),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
  )