gpt4 book ai didi

json - 将 JSON 解码为结构

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

我的问题很小但非常令人沮丧,因为我似乎无法得到答案。我正在尝试访问来自 Google Script 的响应的 JSON 部分。在 Golang 中,我已经设法将它简化为这个

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[
{
"id": 1,
"casenumber": "Criminal Case 20 of 2012",
"datedelivered": "2015-10-22T21:00:00.000Z",
"judge": "George Matatia Abaleka Dulu",
"court": "High Court",
"location": "Garissa",
"accused": "Abdi Sheikh Mohamed",
"judgment": "The accused Abdi Sheikh Mohamed stands charged with the offence of murder contrary to Section 203 as read with Section 204 of the Penal Code. The particulars of the offence are that on 8th May 2012 at Ifo Refugee camp, Lagdera District within Garissa County murdered Othon Ubang Alwal. He has denied the charge."
},
{
"id": 2,
"casenumber": "Criminal Case 21 of 2012",
"datedelivered": "2015-11-22T21:00:00.000Z",
"judge": "Lilo",
"court": "High Court",
"location": "Nairobi",
"accused": "Stitch",
"prosecution": "Milo",
"judgment": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
}
]]

但我需要通过去掉

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[

所以我只有结果部分。

到目前为止,我已经尝试将它解码到我的结构中,但没有成功。这是结构

type Case struct {
ID int
CaseNumber string
DateDelivered string
Judge string
Court string
Location string
Accused string
Prosecution string
Judgment string
}

我们将不胜感激任何帮助。

编辑:解码部分的意思是当我尝试解码到我的结构时(即使在修复结构之后)我得到错误

json: cannot unmarshal object into Go value of type []Case

这是我需要开始工作的代码 http://play.golang.org/p/rmsvfPVx52 .

最佳答案

您需要export通过以大写字符开头的名称来区分 Case 中的字段。

type Case struct {
ID int
CaseNumber string
DateDelivered string
Judge string
Court string
Location string
Accused string
Prosecution string
Judgment string
}

encoding/json 包和类似的包会忽略未导出的字段。

使用 slice 解码 JSON 数组:

  var result []Case
err := json.Unmarshal(data, &result)
if err != nil {
// handle error
}

Playground Example

关于json - 将 JSON 解码为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33885191/

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