json - 用大数组解析 json

标签 json go

官方指南只是展示了一个简单的例子来解析一个大数组的 json:

[ // eat this
    {"Name": "Ed", "Text": "Knock knock."},     /*
    {"Name": "Sam", "Text": "Who's there?"},    *
    {"Name": "Ed", "Text": "Go fmt."},          * parse this part one by one
    {"Name": "Sam", "Text": "Go fmt who?"},     *
    {"Name": "Ed", "Text": "Go fmt yourself!"}  */
] // eat this
但是这种方式不能在我的json中使用:
{
"A":[
    {"a":"xxx","b":"xxx"}    /* A is useless. */
],
"B":[    
    {"c":"xxx","d":"xxx"},    /*
    {"c":"xxx","d":"xxx"},    * B has thousands of children.
    {"c":"xxx","d":"xxx"}     */
    ...
]
}
如何逐个解析B中的 child (而不是将它们全部读入内存)

最佳答案

如果我正确理解你的问题,也许这个例子会有所帮助
包主

import (
    "fmt"
    "encoding/json"
)
type Example struct {
    B []struct {
        C string `json:"c"`
        D string `json:"d"`
    } `json:"B"`
}
func main() {
    var str = `{"A":[{"a":"xxx","b":"xxx"}],"B":[{"c":"xxx","d":"xxx"},{"c":"xxx","d":"xxx"}]}`
    var     elem Example
    json.Unmarshal([]byte(str),&elem)
    fmt.Printf("elem:%+v",elem)
    
 }

关于json - 用大数组解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63815172/

相关文章:

json - 如何在PowerShell中将HashTable正确转换为JSON?

javascript - Angular JSON post 只发送 json 数组的一项

java - RESTEasy——解码 JSON 时出现 "Unexpected element"?

go - 如何使用 golang 使用 "SCAN"而不是 "KEYS"从 redis 扫描键

java - Spring JsonView 解除嵌套字段

ios - NSDictionary 未获取第一项 JSON

go - 使用 gopacket 更改目标端口

Golang channel 输出顺序

go - 打印/访问超出范围的 slice 索引时不要 panic

postgresql - 插入关系 go-pg PostgreSQL