Вопрос

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)

}
Это было полезно?

Решение

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} 
  }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top