#How do I decode `type`?

1 messages · Page 1 of 1 (latest)

rugged fiber
#

I have an API that returns json with a key named type, how do I decode this into a gleam type?

#

(The struct param has a name of media_type)

mellow jolt
#

What's stopping you decoding it?

rugged fiber
mellow jolt
#

Name it something else then

rugged fiber
#
import gleam/dynamic

pub type ReceiveTag {
  ReceiveTag(name: String, value: String, media_type: String)
}

pub fn receive_encoder() {
  dynamic.decode3(
    ReceiveTag,
    dynamic.field("name", dynamic.string),
    dynamic.field("value", dynamic.string),
    dynamic.field("type", dynamic.string),
  )
}
#

like can I do this?

mellow jolt
#

Yep

rugged fiber
#

oh

#

it won't complain?

mellow jolt
#

Why would it?

#

Although you should use the new decoder API, that one will soon be deprecated

rugged fiber
#

what is the new decoder API?

mellow jolt
#

gleam/dynamic/decode

#

Also the LS can generate decoders for you now

hollow coyote
#

Not the decoder they need though

mellow jolt
#

Pretty close

rugged fiber
#

Why not?

mellow jolt
#

Because the JSON field is called type but the Gleam field is called media_type

#

By default it assumes all the fields match up

rugged fiber
#

I do not see any code actions near the type

mellow jolt
#

If you put your cursor over the name of the type in the definition it should work

#

Provided you're on gleam 1.7

rugged fiber
#

gleam 1.5.1 ah

#

wow fancy it works