Reputation: 45
I have a JSON file as follows:
{
"contracts": [
{
"name": "contract1",
"funcs": [
{
"name": "func1",
"callchain": ["parfunc1", "parfunc2", "parfuncN"],
"stateFuncs": ["stafunc1", "stafunc2", "stafuncN"],
"consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
},
{
"name": "func2",
"callchain": ["2parfunc1", "2parfunc2", "2parfunN"],
"stateFuncs": ["2stafunc1", "2stafunc2", "2stafuncN"],
"consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
]
},
{
"name": "contract2",
"funcs": [
{
"name": "func3",
"callchain": ["parfunc5", "parfunc5", "parfuncN"],
"stateFuncs": ["stafunc8", "stafunc8", "stafuncN"],
"consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
}
]
}
]
}
I encounter the problem json: cannot unmarshal object into Go struct field ContractAll.contracts of type main.ContractInfo
contracts: {[[] []]} with the following unmarshalled codes, where the json_content
contains contents of the JSON file:
type FuncInfo struct {
Name string `json:"name"`
Callchain []string `json:"callchain"`
StateFuncs []string `json:"stateFuncs"`
ConsOnInputs []string `json:"consOnInputs"`
}
type ContractInfo []struct{
Name string `json:"name"`
Funcs []FuncInfo `json:"funcs"`
}
type ContractAll struct {
Contracts []ContractInfo `json:"contracts"`
}
var contracts ContractAll
err = json.Unmarshal([]byte(json_content), &contracts)
How can I fix this problem?
Upvotes: 0
Views: 1953
Reputation: 51577
Your structures don't match the input. You need one more:
type Contracts struct {
Contracts []ContractInfo `json:"contracts"`
}
...
var contracts Contracts
err = json.Unmarshal([]byte(json_content), &contracts)
Upvotes: 1