英文:
Golang - How do you decode json array and get the root property
问题
我无法解码这个Go中的JSON。映射返回nil。虽然Unmarshal可以从内存中工作,但最终我可能需要一个流。此外,我需要获取Foo、Bar和Baz键名。对此不太确定。
JSON:
{
  "Foo" : {"Message" : "Hello World 1", "Count" : 1}, 
  "Bar" : {"Message" : "Hello World 2", "Count" : 0}, 
  "Baz" : {"Message" : "Hello World 3", "Count" : 1} 
}
代码:
package main
import (
	"encoding/json"
	"fmt"
	"os"
)
type Collection struct {
	FooBar map[string]Data
}
type Data struct {
	Message string `json:"Message"`
	Count   int    `json:"Count"`
}
func main() {
	//将会是http请求
	file, err := os.Open("stream.json")
	if err != nil {
		panic(err)
	}
	decoder := json.NewDecoder(file)
	var c Collection
	err = decoder.Decode(&c)
	if err != nil {
		panic(err)
	}
	for key, value := range c.FooBar {
		fmt.Println("Key:", key, "Value:", value)
	}
	//返回空映射
	fmt.Println(c.FooBar)
}
英文:
I can't figure out how to decode this JSON in Go. The map returns nil. Unmarshal works from memory, but eventually I might need a stream. Also, I need to get Foo, Bar and Baz key names. Not sure about that one.
JSON:
{
  "Foo" : {"Message" : "Hello World 1", "Count" : 1}, 
  "Bar" : {"Message" : "Hello World 2", "Count" : 0}, 
  "Baz" : {"Message" : "Hello World 3", "Count" : 1} 
}
Code:
package main
import (
	"encoding/json"
	"fmt"
	"os"
)
type Collection struct {
	FooBar map[string]Data
}
type Data struct {
	Message string `json:"Message"`
	Count   int    `json:"Count"`
}
func main() {
	//will be http
	file, err := os.Open("stream.json")
	if err != nil {
		panic(err)
	}
	decoder := json.NewDecoder(file)
	var c Collection
	err = decoder.Decode(&c)
	if err != nil {
		panic(err)
	}
	for key, value := range c.FooBar {
		fmt.Println("Key:", key, "Value:", value)
	}
	//returns empty map
	fmt.Println(c.FooBar)
}
答案1
得分: 3
你不需要一个顶层的结构体,可以直接解码到一个map中:
err = decoder.Decode(&c.FooBar)
或者,直接移除结构体:
type Collection map[string]Data
对于你的顶层结构体,隐含的格式是:
{
  "FooBar": {
    "Foo" : {"Message" : "Hello World 1", "Count" : 1}, 
    "Bar" : {"Message" : "Hello World 2", "Count" : 0}, 
    "Baz" : {"Message" : "Hello World 3", "Count" : 1} 
  }
}
英文:
You don't need a top-level struct, decode directly into a map:
err = decoder.Decode(&c.FooBar)
Or, just remove the struct:
type Collection map[string]Data
With your top-level struct, the implied format is:
{
  "FooBar": {
    "Foo" : {"Message" : "Hello World 1", "Count" : 1}, 
    "Bar" : {"Message" : "Hello World 2", "Count" : 0}, 
    "Baz" : {"Message" : "Hello World 3", "Count" : 1} 
  }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论