如何使用Go部分解析JSON? [英] How to partially parse JSON using Go?

查看:76
本文介绍了如何使用Go部分解析JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json:

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

items[0].inputs基于items[0].type的更改.

知道这一点,是否有办法将inputs字段保留为字符串?想法是使用type调用传递inputs的正确处理程序,然后在其中使用正确的结构解析inputs字符串.

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.

示例:

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
}

谢谢.

推荐答案

使用 json.RawMessage 获取inputs字段的原始JSON文本:

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

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

像这样使用它:

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\n", item.Type, v)

    }
}

在操场上运行.

这篇关于如何使用Go部分解析JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆