dongyao1915 2018-09-10 02:39
浏览 207
已采纳

如何使用Go部分解析JSON?

I have the following json:

{
    "app": {
        "name": "name-of-app",
        "version" 1
    },
    "items": [
        {
            "type": "type-of-item",
            "inputs": {
                "input1": "value1"
            }
        }
    ]
}

The items[0].inputs change based on the items[0].type.

Knowing that, is there a way to keep the inputs field a string? The idea is to use the type to call the right handler passing the inputs, and in there I would parse the inputs string using the right struct.

Example:

package main

import (
    "fmt"
    "encoding/json"
)

type Configuration struct {
    App   App `json:"app"`
    Items []Item `json:"items"`
}

type App struct {
    Name    string `json:"name"`
    Version int    `json:"version"`
}

type Item struct {
    Type string `json:"type"`
    // What to put here to mantain the field a string so I can Unmarshal later?
    // Inputs string
}

var myJson = `
{
    "app": {
        "name": "name-of-app",
        "version": 1
    },
    "items": [
        {
            "type": "type-of-item",
            "inputs": {
                "input1": "value1"
            }
        }
    ]
}
`

func main() {
    data := Configuration{}
    json.Unmarshal([]byte(myJson), &data)

    fmt.Println("done!", data)
    // Loop through data.Items and use the type to define what to call, and pass inputs
    // as argument
}

Thank you in advance.

  • 写回答

3条回答 默认 最新

  • dounayan3643 2018-09-10 03:11
    关注

    Use json.RawMessage to get the raw JSON text of the inputs field:

    type Item struct {
        Type   string `json:"type"`
        Inputs json.RawMessage
    }
    

    Use it like this:

    var data Configuration
    if err := json.Unmarshal([]byte(myJson), &data); err != nil {
        // handle error
    }
    
    // Loop over items and unmarshal items.Inputs to Go type specific
    // to each input type.    
    for _, item := range data.Items {
        switch item.Type {
        case "type-of-item":
            var v struct{ Input1 string }
            if err := json.Unmarshal(item.Inputs, &v); err != nil {
                // handle error
            }
            fmt.Printf("%s has value %+v
    ", item.Type, v)
    
        }
    }
    

    Run it on the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败