如何使用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)
}
}