golang:我如何访问json解码字段?

我有下一个
JSON数据:
http://jsonblob.com/532d537ce4b0f2fd20c517a4

所以我试图迭代(如PHP中的foreach)是:发票 – >发票(是一个数组)

那么,我想要做的是:

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

}

但我收到的错误如:invoices.invoice undefined(type interface {}没有字段或方法发票)

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

所以,我需要一些帮助,这是我与Go的第一天.

非常感谢你.

最佳答案 当你做发票时:= dat [“发票”]发票的类型是接口{},可以说是任何东西.

实际上它是map [string] interface {}.要将接口{}转换为具体类型,您需要像这样使用type assertion.

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

有关完整示例,请参见the playground.

但是,如果这个结构定义得很好(并非所有json都是),那么我将定义一个struct and unmarshal to that,这将使您的代码更容易阅读.不要忘记使用大写字母作为结构名称,然后使用json:“name”标记命名它们(参见tags in the Marshal section of the docs)

点赞