Golang – 如何解码 JSON 数组并获取根属性

huangapple go评论100阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年3月28日 15:27:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/22706680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定