Chris
Chris

Reputation: 18884

Go send null in json

type JobTitles struct {
    Titles []string `json:"titles"`
}

chiefTitles := []string{"CEO", "CFO", null, "CMO"}

jsonOut := JobTitles{chiefTitles}

In the code above, I would like to be able to send null as one of the values in my json string array. However, the above will not compile and if I add double quotes to null it becomes a string not the value null.

How can I send null in my json response in GO?

This article seems to help, but looks to be the inverse of my question..

Upvotes: 4

Views: 3674

Answers (2)

evanmcdonnal
evanmcdonnal

Reputation: 48114

In order to represent that type with the value 'null' it would have to be a pointer. The problem isn't that you can't use null but rather that a string can't have that value. Here is a quick example I made in the playground; https://play.golang.org/p/SXO5sBl2mR

package main

import "fmt"
import "encoding/json"

type Test struct {
    A *string
    B *string
}

func main() {
        s := "Something"
        t := Test{A:&s, B:nil}
        b, err := json.Marshal(t)
        if err != nil {
            fmt.Println(err)
        }
    fmt.Println(string(b))
}

As DaveC mentioned using pointers makers the initilization a bit more cumbersome but you can use the same type of constructs I have above; declare a string, use the & that string in the composite literal.

Upvotes: 4

OneOfOne
OneOfOne

Reputation: 99332

You will have to use *string instead, and create a helper function to make it easier, something along the lines of:

func main() {
    chiefTitles := []*string{sP("CEO"), sP("CFO"), nil, sP("CMO")}

    b, _ := json.Marshal(JobTitles{chiefTitles})

    fmt.Println(string(b))
}

type JobTitles struct {
    Titles []*string `json:"titles"`
}

func sP(s string) *string {
    return &s
}

playground

Upvotes: 3

Related Questions