简体   繁体   中英

Parse a Json file with golang, encountering a problem “cannot unmarshal object into Go value of type”

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM