英文:
Can't unmarshall JSON with key names having spaces
问题
我明白你的问题。你遇到的问题是,使用标准的encoding/json
库解析JSON数据时,无法理解带有空格的键名。在你提供的代码中,库会移除键名中的空格(例如Na me),然后尝试查找键名为Name的键,但实际上并不存在这个键。你想知道有什么建议可以解决这个问题。
要解决这个问题,你可以使用json.Unmarshal
函数的json:""
标签来指定结构体字段与JSON键之间的映射关系。在这种情况下,你可以将结构体字段的json:""
标签设置为键名中带有空格的形式,如下所示:
type Animal struct {
Name string `json:"Na me"`
Order string `json:"Order,omitempty"`
}
通过这样的设置,encoding/json
库就能正确地将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)
}
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?
答案1
得分: 7
你的json
标签规范是错误的,这就是为什么encoding/json
库默认使用字段名Name
。但由于没有带有"Name"
键的JSON字段,Animal.Name
将保持其零值(即空字符串""
)。
解组Order
仍然可以工作,因为如果缺少json
标签规范,json
包将使用字段名(尝试使用小写和大写)。由于字段名与JSON键相同,因此无需额外的JSON标签映射即可正常工作。
在冒号后和引号前的标签规范中不能有空格:
type Animal struct {
Name string `json:"Na me"`
Order string `json:"Order,omitempty"`
}
通过这个简单的更改,它可以工作(在Go Playground上尝试一下):
[{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
英文:
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}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论