icn
icn

Reputation: 17876

Golang setting a simple json string

What is the easy way to construct a simple json to send to client http response

How about this

json.Marshal(`{}`)

Is there a better way to send am simple json object to http response?

Thanks for help

Upvotes: 0

Views: 1063

Answers (1)

erik258
erik258

Reputation: 16304

"{}" is already a string and valid JSON, so you don't need to call json.Marshal.

If you wanted to use json.Marshal, you could use something that would render out the same way, like a literal map[string]interface{}{}.

    j, err := json.Marshal(map[string]interface{}{})
    if err != nil {
        panic(err)
    } else {
        fmt.Println(string(j))
    }

For a full example see https://go.dev/play/p/GI4JlW9hu1q

Upvotes: 1

Related Questions