V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
SenLief
V2EX  ›  Go 编程语言

请教一个 json 转结构体的问题

  •  
  •   SenLief · 2022-05-17 23:05:15 +08:00 · 1808 次点击
    这是一个创建于 680 天前的主题,其中的信息可能已经有所发展或是发生改变。

    json 如下

    {
        "pre1":{
            "code":1
        },
        "pre2":{
            "code":2
        }
    }
    

    这个 json 文件有很多个 pre 的 key ,而且是动态添加的,这种的结构体如何构建呢?

    第 1 条附言  ·  2022-05-18 01:07:37 +08:00
    2 楼、3 楼
    9 条回复    2022-05-26 10:43:46 +08:00
    lessMonologue
        1
    lessMonologue  
       2022-05-17 23:16:56 +08:00
    用数组保存 pre ,pre 里再加个字段保存每个 pre 的类型或者字段名,eg
    ```json
    {
    "pre":[
    {
    "type": "pre1",
    "code": 1
    },
    {
    "type": "pre2",
    "code": 2
    },
    ....
    ]
    }
    ```
    Gota
        2
    Gota  
       2022-05-17 23:20:21 +08:00
    ``` go
    type Raw map[string]struct {
    Code int64 `json:"code"`
    }
    ```
    foam
        3
    foam  
       2022-05-17 23:20:49 +08:00 via Android
    定义一个 map 就好啦
    SenLief
        4
    SenLief  
    OP
       2022-05-17 23:20:58 +08:00
    @lessMonologue 我也测试出来了这个,就是感觉有点割裂,不能像其他语言那样直接读取出来的吗?这样的 pre 感觉就是孤零零的一个键。

    或者说 go 一般使用 json 做配置文件的时候通用的格式类似于什么样的?
    lessMonologue
        5
    lessMonologue  
       2022-05-17 23:23:53 +08:00
    @Gota @foam @SenLief 其实我也一直在找这种类型的 json 最佳实现,看起来应该是 map 更好一点😂
    SenLief
        6
    SenLief  
    OP
       2022-05-17 23:37:24 +08:00
    @Gota
    @foam 多谢 我试试,不过读出来后把 pre 做 key ,其余的全部是 value 了,这样也不行。
    SenLief
        7
    SenLief  
    OP
       2022-05-18 01:06:54 +08:00
    @Gota
    @foam 不好意思,我的锅,写错了,现在可以了,多谢!
    Joker123456789
        8
    Joker123456789  
       2022-05-25 14:05:49 +08:00
    这不就是个数组
    SenLief
        9
    SenLief  
    OP
       2022-05-26 10:43:46 +08:00
    @Joker123456789 map 吧,不过因为我还要修改,所以还是用了 map[string]*struct 这种的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3246 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:43 · PVG 19:43 · LAX 04:43 · JFK 07:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.