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

时间:2014-03-22 09:35:58

标签: go

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

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

所以,我想做的是:

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(类型接口{}没有字段或方法发票)

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

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

非常感谢。

1 个答案:

答案 0 :(得分:2)

当您执行invoices := dat["invoices"] invoices的类型为interface{}时,可以说任何事情。

实际上它是map[string]interface{}。要将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