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.
Try gjson, super simple, you do not have to unmarshal the whole thing. you can take the bytes and pull a specific field out. https://github.com/tidwall/gjson
In fairness Go would actually parse partially if you defined a partial struct. Quoting the documentation (https://blog.golang.org/json-and-go):
Use json.RawMessage to get the raw JSON text of the
inputs
field:Use it like this:
Run it on the playground.