Sjors Hijgenaar
Sjors Hijgenaar

Reputation: 1322

JSON unmarshal in nested struct

I am trying to unmarshal an incoming JSON into a struct that contains an array of structs. However I get the error

"Invalid input. JSON badly formatted. json: cannot unmarshal array into Go struct field DataInput.Asset of type app.AssetStorage"

I have tried to recreate the code here: https://play.golang.org/p/RuBaBjPmWxO, however I can't reproduce the error (although the incoming message and code are identical).

type AssetStorage struct {
    Event         string   `json:"Event"`
    EmployeeID    int      `json:"EmployeeID"`
    EmployeeEmail string   `json:"EmployeeEmail"`
    PerformedBy   string   `json:"PerformedBy"`
    Timestamp     string   `json:"Timestamp"`
    AlgorithmID   string   `json:"AlgorithmID"`
    AlgorithmHash string   `json:"AlgorithmHash"`
    Objects       []Object `json:"Objects"`
}

type Object struct {
    ShortName   string `json:"ShortName"`
    Hash        string `json:"Hash"`
    DestroyDate string `json:"DestroyDate"`
}

type DataInput struct {
    Username string
    Token    string       `json:"Token"`
    Asset    AssetStorage `json:"Asset"`
}

func main() {
    var data DataInput
    json.Unmarshal(input, data)
    data.Username = data.Asset.EmployeeEmail
    fmt.Printf("%+v\n", data)
}

Upvotes: 1

Views: 2178

Answers (2)

Himanshu
Himanshu

Reputation: 12675

There are three bugs in your code, one is that your are not using address of DataInput struct when you are unmarshalling your JSON.

This should be:

var data DataInput
json.Unmarshal(input, data)

like below:

var data DataInput
if err := json.Unmarshal(input, &data); err != nil {
    log.Println(err)
}

One Piece of advice in above code. Never skip errors to know more about the error

Next as the error says:

Invalid input. JSON badly formatted. json: cannot unmarshal array into Go struct field DataInput.Asset of type app.AssetStorage

DataInput.Asset should be an array of json objects there you should change your AssetStorage to []AssetStorage in your declaration in DataInput struct.

One more error is that you are declaring the type of EmployeeID field for AssetStorage struct to be an int which should be a string

Working Code on Go Playground

Upvotes: 3

Alex Guerra
Alex Guerra

Reputation: 2736

The answer is in the error message:

Invalid input. JSON badly formatted. json: cannot unmarshal array into Go struct field DataInput.Asset of type app.AssetStorage

The json you're parsing has DataInput.Asset as an array of AssetStorage objects. So, the type needs to be []AssetStorage.

Upvotes: 0

Related Questions