英文:
How can I ignore root JSON Element in go?
问题
我想将以下JSON序列化为map[string]string,其中map["Name"] == "Value"。
{
"Item": {
"tags": {
"Name": "Value"
}
}
}
然而,我不想创建一个只有一个字段"item"的结构体。在Go语言中是否有类似Java/Jackson的方法可以忽略JSON的根元素,例如mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
?
目前我找到的最好的方法是:
items := make(map[string]map[string]string)
items := items["Item"]
希望对你有帮助!
英文:
I would like to serialize the following JSON into a map[string]string with map["Name"] == "Value"
{
"Item": {
"tags": {
"Name": "Value"
}
}
}
However, I want to not have to create a strut with one field for "item". Is it possible to ignore the root JSON element in go similar to Java/Jackson: mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
The best I have so far is:
items := make(map[string]map[string]string)
items := items["Item"]
答案1
得分: 6
我会为你翻译以下内容:
我会创建一个小助手,用于跳过结构体的根部分,代码如下:
func SkipRoot(jsonBlob []byte) json.RawMessage {
var root map[string]json.RawMessage
if err := json.Unmarshal(jsonBlob, &root); err != nil {
panic(err)
}
for _, v := range root {
return v
}
return nil
}
然后像这样使用它:
json.Unmarshal(SkipRoot(jsonBlob), &items)
完整示例请参考:[Playground](http://play.golang.org/p/8wwpwwX4TQ)
英文:
<!-- language: go -->
I would make a small helper that will skip the root of the structure around the lines of:
func SkipRoot(jsonBlob []byte) json.RawMessage {
var root map[string]json.RawMessage
if err := json.Unmarshal(jsonBlob, &root); err != nil {
panic(err)
}
for _, v := range root {
return v
}
return nil
}
Then use it like that :
json.Unmarshal(SkipRoot(jsonBlob), &items)
Full example here : Playground
答案2
得分: 1
很抱歉,encoding/json
包没有任何功能可以忽略根元素。最简单的方法是使用你提到的那些不需要的结构体:
type Root struct {
Item Item
}
type Item struct {
Tags map[string]string
}
这是一个完整的工作示例:
package main
import (
"encoding/json"
"fmt"
)
type Root struct {
Item Item
}
type Item struct {
Tags map[string]string
}
var data = []byte(`{
"Item": {
"tags": {
"Name": "Value"
}
}
}`)
func main() {
var s Root
if err := json.Unmarshal(data, &s); err != nil {
panic(err)
}
tags := s.Item.Tags
fmt.Printf("%+v", tags)
}
输出
map[Name:Value]
英文:
Unfortunately, no.
The encoding/json
package doesn't have any feature allowing you to ignore the root element. The easiest way is to use those unwanted structs you mentioned:
type Root struct {
Item Item
}
type Item struct {
Tags map[string]string
}
Here is a full working example:
package main
import (
"encoding/json"
"fmt"
)
type Root struct {
Item Item
}
type Item struct {
Tags map[string]string
}
var data = []byte(`{
"Item": {
"tags": {
"Name": "Value"
}
}
}`)
func main() {
var s Root
if err := json.Unmarshal(data, &s); err != nil {
panic(err)
}
tags := s.Item.Tags
fmt.Printf("%+v", tags)
}
Output
>map[Name:Value]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论