i have the next JSON data: http://jsonblob.com/532d537ce4b0f2fd20c517a4
So what im trying to iterate ( like foreach in PHP ) is: invoices -> invoice ( is an array )
So, what im 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("
JSON-VALUE:",json_string)
fmt.Println("
Var type:",invoices)
fmt.Println("
Var type using REFLECT:",reflect.TypeOf(invoices))
for index,value := range invoices.invoice {
fmt.Println(index,value)
}
}
but im receiving errors like: invoices.invoice undefined (type interface {} has no field or method invoice)
http://play.golang.org/p/8uTtN6KtTq
So please, i need some help here, is my first day with Go.
Thank you very much.
When you did invoices := dat["invoices"]
the type of invoices
is interface{}
which is go speak for could be anything.
In actual fact it is a map[string]interface{}
. To turn an interface{}
into it's concrete type you need to use a type assertion like this.
for index,value := range invoices.(map[string]interface{}) {
fmt.Println(index,value)
}
See the playground for full example.
However if this structure is well defined (not all json is) then I'd define a struct and unmarshal to that which will make your code a lot easier to read. Don't forget to use Capital letters for your struct names and then name them with the json:"name"
tags (see tags in the Marshal section of the docs)