将JSON解组为结构体

huangapple go评论105阅读模式
英文:

Unmarshal JSON into struct

问题

我的问题很小,但非常令人沮丧,因为我似乎无法得到答案。我正在尝试访问来自Google脚本的响应的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。

英文:

My issue is very small but very frustrating since I can't seem to get the answer. I am trying to access the JSON part of a response from Google Script. In Golang, I have managed to strip it down to this

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"
}
]]

but I need to strip it down one level further by getting rid of

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

so I only have the results part.

So far I have tried unmarshalling it to my struct with no success. Here is the struct

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

Any help will be highly appreciated.

EDIT: What I meant by the unmarshaling part is that when I try unmarshaling into my struct (even after fixing the struct) I get the error

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

This is the code I need to get to work http://play.golang.org/p/rmsvfPVx52.

答案1

得分: 2

你需要通过将字段的名称以大写字母开头来导出 Case 结构体中的字段。

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

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

使用切片来解码 JSON 数组:

var result []Case
err := json.Unmarshal(data, &result)
if err != nil {
   // 处理错误
}

Playground 示例

英文:

You need to export the fields in Case by starting the name with an uppercase character.

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

The encoding/json package and similar packages ignore unexported fields.

Use a slice to decode a JSON array:

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

<kbd>Playground Example</kbd>

答案2

得分: 0

c是一个包含两个案例的映射。每个案例都有以下属性:

案例1:

  • ID:1
  • 案件编号:Criminal Case 20 of 2012
  • 交付日期:2015-10-22T21:00:00.000Z
  • 法官:George Matatia Abaleka Dulu
  • 法院:High Court
  • 地点:Garissa
  • 被告:Abdi Sheikh Mohamed
  • 判决:被告Abdi Sheikh Mohamed被控犯有谋杀罪,违反了刑法第203条和第204条的规定。犯罪的具体情节是,在2012年5月8日,在Garissa县的Lagdera区的Ifo难民营内,谋杀了Othon Ubang Alwal。他否认了指控。

案例2:

  • ID:2
  • 案件编号:Criminal Case 21 of 2012
  • 交付日期:2015-11-22T21:00:00.000Z
  • 法官:Lilo
  • 法院:High Court
  • 地点:Nairobi
  • 被告:Stitch
  • 检方:Milo
  • 判决: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。
英文:

Where c is

map[@type:type.googleapis.com/google.apps.script.v1.ExecutionResponse result:[
{
    &quot;id&quot;: 1,
    &quot;casenumber&quot;: &quot;Criminal Case 20 of 2012&quot;,
    &quot;datedelivered&quot;: &quot;2015-10-22T21:00:00.000Z&quot;,
    &quot;judge&quot;: &quot;George Matatia Abaleka Dulu&quot;,
    &quot;court&quot;: &quot;High Court&quot;,
    &quot;location&quot;: &quot;Garissa&quot;,
    &quot;accused&quot;: &quot;Abdi Sheikh Mohamed&quot;,
    &quot;judgment&quot;: &quot;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.&quot;
},
{
    &quot;id&quot;: 2,
    &quot;casenumber&quot;: &quot;Criminal Case 21 of 2012&quot;,
    &quot;datedelivered&quot;: &quot;2015-11-22T21:00:00.000Z&quot;,
    &quot;judge&quot;: &quot;Lilo&quot;,
    &quot;court&quot;: &quot;High Court&quot;,
    &quot;location&quot;: &quot;Nairobi&quot;,
    &quot;accused&quot;: &quot;Stitch&quot;,
    &quot;prosecution&quot;: &quot;Milo&quot;,
    &quot;judgment&quot;: &quot;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&quot;
}
]]

I did;

case:= c.(map[string]interface {})
fmt.Println(case[&quot;result&quot;])

which gives;

[
{
    &quot;id&quot;: 1,
    &quot;casenumber&quot;: &quot;Criminal Case 20 of 2012&quot;,
    &quot;datedelivered&quot;: &quot;2015-10-22T21:00:00.000Z&quot;,
    &quot;judge&quot;: &quot;George Matatia Abaleka Dulu&quot;,
    &quot;court&quot;: &quot;High Court&quot;,
    &quot;location&quot;: &quot;Garissa&quot;,
    &quot;accused&quot;: &quot;Abdi Sheikh Mohamed&quot;,
    &quot;judgment&quot;: &quot;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.&quot;
},
{
    &quot;id&quot;: 2,
    &quot;casenumber&quot;: &quot;Criminal Case 21 of 2012&quot;,
    &quot;datedelivered&quot;: &quot;2015-11-22T21:00:00.000Z&quot;,
    &quot;judge&quot;: &quot;Lilo&quot;,
    &quot;court&quot;: &quot;High Court&quot;,
    &quot;location&quot;: &quot;Nairobi&quot;,
    &quot;accused&quot;: &quot;Stitch&quot;,
    &quot;prosecution&quot;: &quot;Milo&quot;,
    &quot;judgment&quot;: &quot;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&quot;
}
]

答案3

得分: 0

如@CodingPickle上面所指示的,你需要先去掉非有效的json:

data := `{&quot;result&quot;:[
{
    &quot;id&quot;: 1,
    ...
},
{
    &quot;id&quot;: 2,
    ...
}]}`

此外,你需要将json定义添加到结构体中:

type Result struct {
    Result []Case `json:&quot;result&quot;`
}

type Case struct {
    ID            int    `json:&quot;id&quot;`
    CaseNumber    string `json:&quot;casenumber&quot;`
    DateDelivered string `json:&quot;datedelivered&quot;`
    Judge         string `json:&quot;judge&quot;`
    Court         string `json:&quot;court&quot;`
    Location      string `json:&quot;location&quot;`
    Accused       string `json:&quot;accused&quot;`
    Prosecution   string `json:&quot;prosecution&quot;`
    Judgment      string `json:&quot;judgement&quot;`
}

示例:

http://play.golang.org/p/KUbDpSxMVI

英文:

As @CodingPickle indicated above, you need to strip the non-valid json first:

data := `{&quot;result&quot;:[
{
    &quot;id&quot;: 1,
    ...
},
{
    &quot;id&quot;: 2,
    ...
}]}`

As well, you need to add the json defn's to the struct:

type Result struct {
    Result []Case `json:&quot;result&quot;`
}

type Case struct {
    ID            int    `json:&quot;id&quot;`
    CaseNumber    string `json:&quot;casenumber&quot;`
    DateDelivered string `json:&quot;datedelivered&quot;`
    Judge         string `json:&quot;judge&quot;`
    Court         string `json:&quot;court&quot;`
    Location      string `json:&quot;location&quot;`
    Accused       string `json:&quot;accused&quot;`
    Prosecution   string `json:&quot;prosecution&quot;`
    Judgment      string `json:&quot;judgement&quot;`
}

Example:

http://play.golang.org/p/KUbDpSxMVI

huangapple
  • 本文由 发表于 2015年11月24日 11:58:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/33885191.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定