无法用具有空格的键名解组JSON [英] Can't unmarshall JSON with key names having spaces
问题描述
我得到的一些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: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屋!