dongping1012 2018-10-29 18:48
浏览 1613

为什么Go json.Marshal拒绝这些struct标签? json标签的正确语法是什么? [重复]

This question already has an answer here:

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"

https://play.golang.org/p/eFe03_89Ly9

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?

</div>
  • 写回答

1条回答 默认 最新

  • dou7466 2018-10-29 19:00
    关注

    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))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog