dongqieli4164 2017-10-26 15:38
浏览 53
已采纳

用自定义struct标签中的空格解组Json [重复]

This question already has an answer here:

I am attempting to unmarshal data in Golang and I'm finding a strange behaviour when some key of the Json object has an underscore (_) in it.

To give an example:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var jsonBlob = []byte(`{"name": "Quoll", "order": "Dasyuromorphia"}`)
    type Animal struct {
        Name  string `json: "name"`
        Order string  `json: "order"`
    }
    var animal Animal
    err := json.Unmarshal(jsonBlob, &animal)
    if err != nil {
        fmt.Println("error:", err)
    }
fmt.Printf("%+v", animal)
}

This runs wonderfully. However, if I change some key to include an underscore:

 var jsonBlob = []byte(`{"name": "Quoll", "order_": "Dasyuromorphia"}`)

And I wanted this to be included into Animal.Order, I am attempting:

type Animal struct {
    Name  string `json: "name"`
    Order string  `json: "order_"`
}

and I am failing miserably to read the data. How can I map arbirary keys to the element I want of my struct? Here's a link to the playground with the example.

</div>
  • 写回答

1条回答 默认 最新

  • duanhuang4306 2017-10-26 15:45
    关注

    It has nothing to do with the underscore. In a struct tag, you can't have a space between the colon and quote, e.g. json:"name". In the first (working) example, the json tags are still ignored; it just happens that the automatic logic works with the field names. If you remove the space after the colon in the struct tags, it works as expected with the latter example.

    See working example here: https://play.golang.com/p/QXdlVsi166

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题