JSON marshal/unmarshall multiple different structs


I would like to be able to store multiple different structs in a JSON file that I can read in to perform specific operations. One of the structs has multiple fields, e.g.:

type copyFile struct {
    Src string            `json:"src"`
    Dst string            `json:"dst"`
    Sudo bool             `json:"sudo"`
    OverWrite bool        `json:"overwrite"`

And another struct that is just user commands, e.g.:

type userCommand struct {
    Cmd string          `json:"cmd"`

If I put them both in an array and json.Marshal them I get something along the lines of:

[{“cmd”:“echo user command”},{“src”:"/dir/src",“dst”:"/dir/dst",“sudo”:true,“overwrite”:false}]

How would I Unmarshal that?

For now I’ve changed the copyFile struct to:

type copyFile struct {
    Cmd string         `json:"copy"`

I then catenate the src, dst, sudo and overwrite with a separator which then allows me to Unmarshal the whole thing with:

x, _ := json.Marshal(commandsArray)
var data []map[string]string
err := json.Unmarshall(x,&data)

Which works and I can just strings.Split() the copyFile Cmd. I just didn’t know if there’s another way to do this that would maintain the structs.

Does anyone have any suggestions? I’m new to Go, so I’m tapping around in the dark at the moment.



Even if I leave the current copyFile struct as a single Cmd string, like the userCommand, I would keep them separate. Part of the reason is that I can “label” the action to take via the map key from the JSON file. For example, if the copyFile is a single string with a separator (in this example: “%”), I would end up with:

[{“copy”:"/dir/src%/dir/dst%true%false"},{“cmd”:“echo user command”}]

Then after Unmarshaling the data I can tell what operation to perform based on the key. If the objects were all represented by the same struct, there would be (at least not that I’m aware of) no way to label them differently.


You could have a really simple struct

typedef cmd struct {
   Cmd string `json:"cmd"`
   Args []string `json:"args"`

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.