gpt4 book ai didi

arrays - 如何解码 json 并填充到 golang 中的结构

转载 作者:数据小太阳 更新时间:2023-10-29 03:44:29 25 4
gpt4 key购买 nike

如何解码 json 并填充到结构中。就像我有 salesorder 和 salesorderdetails 结构。在 json 中,我将有 1 个 salesorder 记录和 salesorderdetails 结构的多个项目。

这是我尝试过对单个项目和多个项目进行测试的代码,但仅适用于 salesorderdetails 结构的单个记录。

Gocode:

package main

import (
"encoding/json"
"fmt"
)

type Order struct {
SalesId string `json:"sales_id"`
Customer string `json:"customer_name"`
TotalPrice string `json:"totalprice"`
}
type OrderDetails struct {
DetailId string `json:"detail_id"`
SalesId string `json:"sales_id"`
ItemName string `json:"item_name"`
Qty string `json:"qty"`
Price string `json:"price"`
}
type Temp struct {

Salesorder Order `json:"Salesorder"`
Salesorderdetails OrderDetails `json:"OrderDetails"`
}

func main() {
jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"}}]`)

//if i use above json it is working and if i use below json its not working
//jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"},{"detailid":"2","sales_id":"SOO2","item_name":"ITEM2","qty":"3","price":"200"}}]`)

var temp []Temp
err := json.Unmarshal(jsonByteArray, &temp)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", temp)
fmt.Printf("%+v\n ", temp[0].Salesorder.SalesId)
}

使用多个项目时出错:

panic: invalid character '{' looking for beginning of object key string

成功使用单个项目时的输出:

[{Salesorder:{SalesId:SOO1 Customer:CUST1 TotalPrice:200} Salesorderdetails:{SalesId:SOO1 ItemName:ITEM1 Qty:2 Price:100}}]
SOO1

Fiddle:使用 salesorderdetails 中的键更新

https://play.golang.org/p/klIAoNi18r

最佳答案

您要解码的内容不是有效的 JSON。这是有效的:

{
"Salesorder": {
"sales_id": "SOO1",
"customer_name": "CUST1",
"totalprice": "200"
},
"OrderDetails": {
"sales_id": "SOO1",
"item_name": "ITEM1",
"qty": "2",
"price": "100"
}
}

但是你给的是这个:

{
"Salesorder": {
"sales_id": "SOO1",
"customer_name": "CUST1",
"totalprice": "200"
},
"OrderDetails": {
"sales_id": "SOO1",
"item_name": "ITEM1",
"qty": "2",
"price": "100"
},
{ // Things become invalid here
"sales_id": "SOO2",
"item_name": "ITEM2",
"qty": "3",
"price": "200"
}
}

看起来您正在尝试提供对象列表,在这种情况下,您需要将这些对象括在方括号 [] 中,否则您将不得不提供第二个 OrderDetails 对象它自己的键。

关于arrays - 如何解码 json 并填充到 golang 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47166270/

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