簡體   English   中英

在Go中將JSON解組到地圖中

[英]Unmarshal JSON into a map in Go

我在弄清楚如何將JSON文件的“小節”加載到地圖元素中時遇到了麻煩。 背景:我正在嘗試解封具有嚴格結構的有些復雜的配置文件,因此我認為最好將其解封為“靜態”結構,而不是解封為接口{}。

這是一個簡單的JSON文件,例如:

{
    "set1": {
        "a":"11",
        "b":"22",
        "c":"33"
    }
}

此代碼有效:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type JSONType struct {
    FirstSet ValsType `json:"set1"`
}

type ValsType struct {
    A string `json:"a"`
    B string `json:"b"`
    C string `json:"c"`
}

func main() {
    file, e := ioutil.ReadFile("./test1.json")
    if e != nil {
        fmt.Println("file error")
        os.Exit(1)
    }
    var s JSONType
    json.Unmarshal([]byte(file), &s)
    fmt.Printf("\nJSON: %+v\n", s)
}

但這不是:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type JSONType struct {
    FirstSet ValsType `json:"set1"`
}

type ValsType struct {
    Vals map[string]string
}

func main() {
    file, e := ioutil.ReadFile("./test1.json")
    if e != nil {
        fmt.Println("file error")
        os.Exit(1)
    }

    var s JSONType
    s.FirstSet.Vals = map[string]string{}
    json.Unmarshal([]byte(file), &s)
    fmt.Printf("\nJSON: %+v\n", s)
}

未加載Vals地圖。 我究竟做錯了什么? 謝謝你的幫助!

這是一個更好的例子:

{
    "set1": {
        "a": {
            "x": "11",
            "y": "22",
            "z": "33"
        },
        "b": {
            "x": "211",
            "y": "222",
            "z": "233"
        },
        "c": {
            "x": "311",
            "y": "322",
            "z": "333"
        },
    }
}

碼:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type JSONType struct {
    FirstSet map[string]ValsType `json:"set1"`
}

type ValsType struct {
    X string `json:"x"`
    Y string `json:"y"`
    Z string `json:"z"`
}

func main() {
    file, e := ioutil.ReadFile("./test1.json")
    if e != nil {
        fmt.Println("file error")
        os.Exit(1)
    }
    var s JSONType
    json.Unmarshal([]byte(file), &s)
    fmt.Printf("\nJSON: %+v\n", s)
}

我相信這是因為您的模型中具有額外的間接層。

type JSONType struct {
    FirstSet map[string]string `json:"set1"`
}

應該足夠了。 如果指定map[string]string ,則json中的對象將被識別為該地圖。 您創建了一個結構來包裝它,但是像這樣的json塊;

{
    "a":"11",
    "b":"22",
    "c":"33"
}

實際上可以直接將其解編為map[string]string

編輯:基於注釋的其他一些模型

type JSONType struct {
    FirstSet map[string]Point `json:"set1"`
}

type Point struct {
     X string `json:"x"`
     Y string `json:"y"`
     Z string `json:"z"`
}

這會使您的3維點成為靜態類型的結構,這很好。 如果您想快速又臟亂地使用,也可以使用map[string]map[string]string來提供地圖圖,這樣您就可以訪問諸如FirstSet["a"]["x"]和它將返回"11"

第二次編輯; 顯然,由於上面的示例是相同的,所以我沒有仔細閱讀過您的代碼。 基於此,我想您想要

 FirstSet map[string]map[string]string `json:"set1"`

選項。 盡管您修改后對我來說還不是很清楚。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM