2017-10-01 8 views
-1

私は、構造体golangのjsonからキーと値にアクセスするには?

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) 

答えて

2

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) 
} 
+0

customerMobileキーの値にアクセスする方法 –

+0

@helloworld 'things [0] .Record.CustomerMobile'はあなたにキーを与えます。詳細 - https://play.golang.org/p/kBX6jqdSA- –

0

はこれに試してみる:この場合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 tags

を省略しています
関連する問題