Why Is Go Json. Marshal Rejecting These Struct Tags? What Is Proper Syntax for Json Tags? [Duplicate]

I am trying to use json.Marshal but it refuses to accept my struct tags.

What am I doing wrong?

Here is the source code for "marshal.go"

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json: "name"`
    Age  int    `json: "age"`
}

func main() {
    p := Person{Name: "Alice", Age: 29}
    bytes, _ := json.Marshal(p)
    fmt.Println("JSON = ", string(bytes))
}

I get these error messages from "go vet marshal.go"

./marshal.go:9: struct field tag `json: "name"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
./marshal.go:10: struct field tag `json: "age"` not compatible with reflect.StructTag.Get: bad syntax for struct tag value

I get this output when I run the program.

% ./marshal
JSON =  {"Name":"Alice","Age":29}

Notice the field names match the Go structure and ignore the json tags.

What am I missing?

4

Oh my goodness! I just figured it out. There is no space allowed between json: and the field name "name".

The "go vet" error message ("bad syntax") is remarkably unhelpful.

The following code works. Can you see the difference?

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func main() {
    p := Person{Name: "Alice", Age: 29}
    bytes, _ := json.Marshal(p)
    fmt.Println("JSON = ", string(bytes))
}
4
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest