簡體   English   中英

如何從Golang中的json訪問鍵和值?

[英]How to access key and value from json in golang?

我有一個結構

type Order struct {
    ID string `json:"id"`
    CustomerMobile string `json:"customerMobile"`
    CustomerName string `json:"customerName"`
   }

和json數據:

[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}] 

如何從上述json對象訪問customerMobile密鑰?

我在Google上進行了一些研究,發現了以下解決方案,但是當我滿足上述要求時,它不起作用。 它使用簡單的json格式。

jsonByteArray := []byte(jsondata)
 json.Unmarshal(jsonByteArray, &order)

您需要解組成代表整個JSON對象的內容。 您的Order結構定義了它的一部分,所以只需定義它的其余部分,如下所示:

package main

import (
    "encoding/json"
    "fmt"
)

type Order struct {
    ID             string `json:"id"`
    CustomerMobile string `json:"customerMobile"`
    CustomerName   string `json:"customerName"`
}

type Thing struct {
    Key    string `json:"Key"`
    Record Order  `json:"Record"`
}

func main() {
    jsonByteArray := []byte(`[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`)
    var things []Thing
    err := json.Unmarshal(jsonByteArray, &things)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", things)
}

嘗試一下: https : //play.golang.org/p/pruDx70SjW

package main

import (
    "encoding/json"
    "fmt"
)

const data = `[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`

type Orders struct {
    Key    string
    Record Order
}

type Order struct {
    ID             string
    CustomerMobile string
    CustomerName   string
}

func main() {
    var orders []Orders
    if err := json.Unmarshal([]byte(data), &orders); err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", orders)
}

在這種情況下,我省略了struct標簽

暫無
暫無

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

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