无法解组带有空格的键名的 JSON [英] Can't unmarshall JSON with key names having spaces

查看:34
本文介绍了无法解组带有空格的键名的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的一些 JSON 数据在键名中有空格.我正在使用标准的 encoding/json 库来解组数据.但是,它无法理解模式中带有空格的键.例如以下代码:

Some JSON data I am getting have spaces in the key names. I am using standard encoding/json library to unmarshal the data. However it is unable to understand the keys with spaces in the schema. For e.g. following code:

package main

import (
    "encoding/json"
    "fmt"
)

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

给出输出为:

[{Name: Order:Monotremata} {Name: Order:Dasyuromorphia}]

因此,在架构中,库删除了空格(从 Name)并尝试找到显然不存在的键 (Name).有什么建议我可以在这里做什么吗?

So in the schema the library removes the space(from Na me) and try to find the key (Name), which is obviously not present. Any suggestion what can I do here?

推荐答案

你的 json 标签规范 不正确,这就是 encoding/json 库默认为字段名称,即Name.但是由于没有带有 "Name" 键的 JSON 字段,Animal.Name 将保持其零值(即空字符串 "").

Your json tag specification is incorrect, that's why the encoding/json library defaults to the field name which is Name. But since there is no JSON field with "Name" key, Animal.Name will remain its zero value (which is the empty string "").

解组 Order 仍然有效,因为如果 json 标签规范缺失,json 包将使用字段名称(尝试使用较低的和大写).由于字段名称与 JSON 键相同,因此无需额外的 JSON 标签映射即可工作.

Unmarshaling Order will still work, because the json package will use the field name if json tag specification is missing (tries with both lower and upper-case). Since the field name is identical to the JSON key, it works without extra JSON tag mapping.

标签规范中冒号后和引号前不能有空格:

You can't have a space in the tag specification after the colon and before the quotation mark:

type Animal struct {
    Name  string `json:"Na me"`
    Order string `json:"Order,omitempty"`
}

通过这个简单的更改,它可以工作(在 Go Playground 上试试):

With this simple change, it works (try it on the Go Playground):

[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]

这篇关于无法解组带有空格的键名的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆