如何在Golang中获取以“@”开头的JSON对象

huangapple go评论68阅读模式
英文:

How to get json object beginning with "@" in Golang

问题

如何获取以“@”开头的 JSON 对象,例如:

{ 
 ...   
 "@meta": {
        "serverTimeMs": 114,
        "requestId": "F45FDGH35HF7"
      }
 ...
}
英文:

How to get json object beginning with "@" like:

{ 
 ...   
 "@meta": {
        "serverTimeMs": 114,
        "requestId": "F45FDGH35HF7"
      }
 ...
}

答案1

得分: 2

如果你想将其解组成一个结构体,你可以使用标签来指定 JSON 键的名称:

type data struct {
  Meta map[string]interface{} `json:"@meta"`
}

示例代码:https://play.golang.org/p/ts6QJac8iH

英文:

If you want to unmarshal it into a struct you can use a tag to specify the name of the json key:

type data struct {
  Meta map[string]interface{} `json:"@meta"`
}

example code: https://play.golang.org/p/ts6QJac8iH

答案2

得分: 2

encoding/json包使用标签来描述JSON对象的编组和解组过程。因此,你应该在结构体上定义一个描述JSON对象的标签以进行解组。而reflect包使用带有StructTag类型的标签。

按照惯例,标签字符串是可选的以空格分隔的键:"值"对的串联。每个键是一个非空字符串,由非控制字符组成,除了空格(U+0020 ' ')、引号(U+0022 '"')和冒号(U+003A ':')。每个值使用U+0022 '"'字符和Go字符串字面值语法进行引用。

标签使用示例

type TargetsResult struct {
    Meta map[string]interface{} `json:"@meta"`
}

func main() {
    var results TargetsResult
    input := `{ "@meta": { "serverTimeMs": 114, "requestId": "F45FDGH35HF7" } }`
    if err := json.Unmarshal([]byte(input), &results); err != nil {
        fmt.Print(err)
    }
    fmt.Printf("%+v\n", results)
}

请注意,json使用reflect来处理标签,因此为了能够在reflect中使用,所有的结构体字段都必须是可导出的(即以大写字母开头)。

英文:

encoding/json package uses tags to describe marshaling/unmarshaling json object. So you should define a tag describing json obj on a struct to unmarshal it. And reflect package uses tags with StructTag type

> By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

Tag usage example:

type TargetsResult struct {
    Meta map[string]interface{} `json:"@meta"`
}

func main() {
    var results TargetsResult
    input := `{ "@meta": { "serverTimeMs": 114, "requestId": "F45FDGH35HF7" } }`
    if err := json.Unmarshal([]byte(input), &results); err != nil {
	     fmt.Print(err)
    }
	fmt.Printf("%+v\n", results)
}

Note, json uses reflect for tags so to be able in reflect all the struct fields must be exportable (i.e. start with uppercase letter).

huangapple
  • 本文由 发表于 2017年1月26日 22:40:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/41875947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定