72 points olexsmir 1 hour ago 12 comments

lolpanda 54 minutes ago | parent

the marshal api has been very annoying. why does marshal return an error? the only reason the marshal can return an error is that the input type is not marshalable. it's certainly a code bug. to me it's like int+str returning an error instead of compiler error

hnlmorg 48 minutes ago | parent

I wouldn’t class unmarshallable data as a compile time error.

Plus the point of the marshal interface is that it’s reusable.

thayne 23 minutes ago | parent

It could be if go had a more powerful type system.

hnlmorg 17 minutes ago | parent

This isn’t a type system problem. It’s a data origin problem. Ie it could be any random JSON blob a user entered. The compiler doesn’t know this ahead of time.

If you wanted type safety with JSON in Go then don’t use the marshal interface. Period.

leetrout 47 minutes ago | parent

JSON is a runtime input of unknown type but in your example those are known types so the compiler can catch them.

NoDodgeQuestion 24 minutes ago | parent

do not know at compile time that input is not marshalable, every language marshal must return error for this reason, not only golang

iaaan 13 minutes ago | parent

It is trivial to ignore an error in Go if you know your use case cannot result in one. But at the end of the day, json.Marshal takes an `any` as a parameter, so it must return an error.

CamouflagedKiwi 48 minutes ago | parent

I generally like `encoding/json/v2` and I'm glad they did it.

I wish they'd left `MarshalIndent` in there though. The equivalent code is super complicated and non-obvious, so it's a pain to migrate, and it's a pain when you're banging out some quick code and want to dump some readable JSON. I suppose these days the LLMs can write the complicated version for us, of course.

athorax 38 minutes ago | parent

I'm not sure if I'm missing something, but isn't this functionality just moved into jsontext? https://pkg.go.dev/encoding/json/jsontext#Value.Indent

  v := jsontext.Value(b)
  v.Indent()
  fmt.Println(string(v))

arccy 14 minutes ago | parent

    json.Marshal(v, jsontext.WithIndent("  "))

?