#How to return dynamic json?

1 messages · Page 1 of 1 (latest)

steel magnet
#

I'm trying to return some json with wisp, but the field called "item" is dynamic and could be anything and is of type a. How do I pass it as a dynamic type here?

 let result = {
        let res_items =
          json.array(items, fn(tag) {
            json.object([
              // something like json.dynamic here
              #("item", json.string(tag.item)),
              #("tag", json.int(tag.tag)),
            ])
          })

        Ok(json.to_string_builder(res_items))
      }

      wisp.json_response(result, 201)
arctic herald
#

You can't have json.dynamic because we need to know how to format it as JSON

#

Dynamic could be anything, including lots of things that are not valid JSON

#

for example, it could be a database connection

#

There's no way to turn that into JSON

steel magnet
#

Makes sense, so instead I need to map all cases to decode them correctly right?

arctic herald
#

That sounds good to me

echo shard
#

Could gleam/json provide an utility to do so?

#

Like a function that guarantees it's valid json, but returns a dynamic?

arctic herald
#

That's would be a very bad idea

#

You should never represent things with Dynamic but attempt to guarentee it is something specific

#

That is going out of your way to avoid the type system

#

If you want to do dynamically typed programming you should use Erlang and not Gleam

#

As Gleam is terrible at untyped programming!

echo shard
#

Uhm, that's true