gpt4 book ai didi

戈朗 : How can i access json decoded field?

转载 作者:IT王子 更新时间:2023-10-29 00:46:37 24 4
gpt4 key购买 nike

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

所以我试图迭代的(就像 PHP 中的 foreach 一样)是:invoices -> 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 未定义(类型接口(interface) {} 没有字段或方法 invoice)

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

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

非常感谢。

最佳答案

当您执行 invoices := dat["invoices"] 时,invoices 的类型是 interface{},它代表 could是任何东西。

实际上它是一个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 )

关于戈朗 : How can i access json decoded field?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22575847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com