关于通过Struct解析嵌套JSON的问题



我有一个有趣的JSON文件,它有点嵌套,我无法找到一个正确解析它的好例子。有人能看看下面的结构是否正确吗?我可以解析根级别的项目,但我越深入就会迷失方向。请参阅下面的代码:

我试图解析的JSON文件在一个单独的文件中:

{
"pushed": 090909099,
"job_id": 17422,
"processed": 159898989,
"unit_report": [
{
"meta": {
"file": {
"file_type": "Binary",
"file_name": "Bob.txt",
"file_path": "/usr/local/Bob.txt",
"size": 4563,
"entropy": 3.877,
"hashes": [
{
"name": "Uniq34",
"value": "02904234234234234243"
},
{
"name": "sha1",
"value": "23423423423423423423423"
},
{
"name": "sha256",
"value": "523412423424234234234"
}
]
},

我的结构设置在下面的Go文件中:

package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
// Report struct
type Report struct {
Pushed int `json:"pushed"`
JobID    int `json:"job_id"`
Processed int `json:"processed"`
SetReport  []struct {
Meta struct {
File struct {
FileType    string `json:"file_type"`
FileName    string `json:"file_name"`
FilePath    string `json:"file_path"`
Size        int    `json:"size"`
Entropy     int    `json:"entropy"`
}
}
}
}

代码的问题是希望json数据中的unit_reportGo结构中的SetReport匹配。

为此,您可以将json:"unit_report设置为SetReport字段,或者将SetReport重命名为UnitReport

任一:

Processed int `json:"processed"`
SetReport  []struct {
...
} `json:"unit_report`  // See the changes here

或:

Processed int `json:"processed"`
UnitReport  []struct { // See the changes here
...
}

最新更新