Golang: How can I access a json-decoded field?

I have the following JSON data: http://jsonblob.com/532d537ce4b0f2fd20c517a4

So what I'm trying to iterate (e.g. foreach in PHP): invoices -> invoice (this is an array)

So what I'm trying to do is:

package main
import (
    "fmt"
    "reflect"
    "encoding/json"
)

func main() {
    json_string := `{"result":"success","totalresults":"494","startnumber":0,"numreturned":2,"invoices":{"invoice":[{"id":"10660","userid":"126","firstname":"Warren","lastname":"Tapiero","companyname":"ONETIME","invoicenum":"MT-453","date":"2014-03-20","duedate":"2014-03-25","datepaid":"2013-07-20 15:51:48","subtotal":"35.00","credit":"0.00","tax":"0.00","tax2":"0.00","total":"35.00","taxrate":"0.00","taxrate2":"0.00","status":"Paid","paymentmethod":"paypalexpress","notes":"","currencycode":"USD","currencyprefix":"$","currencysuffix":" USD"},{"id":"10661","userid":"276","firstname":"koffi","lastname":"messigah","companyname":"Altech France","invoicenum":"","date":"2014-03-21","duedate":"2014-03-21","datepaid":"0000-00-00 00:00:00","subtotal":"440.00","credit":"0.00","tax":"0.00","tax2":"0.00","total":"440.00","taxrate":"0.00","taxrate2":"0.00","status":"Unpaid","paymentmethod":"paypal","notes":"","currencycode":"USD","currencyprefix":"$","currencysuffix":" USD"}]}}`

    var dat map[string]interface{}
    if err := json.Unmarshal([]byte(json_string), &dat); err != nil {
        panic(err)
    }

    invoices := dat["invoices"]

    fmt.Println("\nJSON-VALUE:",json_string)
    fmt.Println("\nVar type:",invoices)
    fmt.Println("\nVar type using REFLECT:",reflect.TypeOf(invoices))

    for index,value := range invoices.invoice {
        fmt.Println(index,value)
    }

}

but im accepts errors like: invoices.invoice undefined (an interface like {} does not contain a count of fields or methods)

http://play.golang.org/p/8uTtN6KtTq

So please, I need help here, this is my first day with Go.

Many thanks.

+4
source share
1 answer

When you did invoices := dat["invoices"], the type invoices- interface{}for which go to speak, could be anything.

map[string]interface{}. interface{} , , .

for index,value := range invoices.(map[string]interface{}) {
    fmt.Println(index,value)
}

. .

, ( json), , . , json:"name" (. )

+2

Source: https://habr.com/ru/post/1532958/


All Articles