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

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

问题描述

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

  package main 

import(
encoding / json
$ f


func main(){
var jsonBlob = [] byte(`[
{Na me:Platypus, Order:Monotremata},
{Na me:Quoll,Order:Dasyuromorphia}
]`)
类型动态结构{
命名字符串`json:Na me`
命令字符串`json:Order,omitempty`
}
var animals [] Animal
err:= json.Unmarshal( jsonBlob,& animals)
if err!= nil {
fmt.Println(error:,err)
}
fmt.Printf(%+ v,动物)
}

给出的结果为:

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

因此,在模式中,数据库将删除空格(来自 Na me )并尝试查找键( Name ),即显然不存在。任何建议我可以在这里做什么?

解决方案

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

解组订单仍然可以工作,因为如果缺少 json 标记指定, json 包将使用字段名称和大写)。由于字段名称与JSON密钥相同,所以它不需要额外的JSON标签映射。



标签规格中的空格不能超过冒号和之前引用标记:

 类型动态结构{
名称字符串`json:Na me`
订单字符串`json:Order,omitempty`
}

它的工作原理(在 Go Playground 上试用):

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


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

Gives the output as:

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

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?

解决方案

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 "").

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"`
}

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

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

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

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