json - 如何使用 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
使用正确的结构解析字符串。
例子:
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 文本:
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)
}
}
推荐阅读
- blazor - 为每个客户端连接设置默认语言文化 blazor-server
- excel - 有没有办法使用同一行中的countifs检查excel中是否满足条件一次
- python - Selenium ChromeDriver 显式等待 visibility_of_element_located 会在 present_of_element_located 不存在时抛出 TimeOut 异常,对于 Select
- jenkins - Jenkins 无法构建 docker 镜像。未找到 script.sh docker
- psql - 如何反转 psql 脚本中特殊参数的默认值?
- r - 如何在r中的数据框中按行对数字数据进行排名?
- git - 使用 update-refs 重命名和修复错误后无法推送分支
- mongodb - 如何使用 $or 使用基于数组中对象的多个条件的投影
- javascript - 如何修复查询选择器 (DOM) 和事件监听器?
- python - 在 tfcausalimpact 中从运行到运行的结果变化