1

I have different json byte inputs that I need to unmarshal into a nested json structure. I am able to unmarshal the json into the struct App. However I am unable to add to "status" struct.

I tried to unmarshal, but that doesnt work since my app1 & app2 are of type App instead of bytes. And trying to set directly gives the error "cannot use app1 (type App) as type []App in assignment"

package main import ( "encoding/json" "fmt" "reflect" ) type App struct { Appname string `json:"appname"` Builds string `json:"builds"` } type Status struct { Apps []App `json:"apps"` } func main() { jsonData1 := []byte(` { "appname": "php1", "buildconfigs":"deleted" } `) jsonData2 := []byte(` { "appname": "php2", "buildconfigs":"exists" } `) // unmarshal json data to App var app1 App json.Unmarshal(jsonData1, &app1) var app2 App json.Unmarshal(jsonData2, &app2) var status Status //json.Unmarshal(app1, &status) //json.Unmarshal(app2, &status) status.Apps = app1 status.Apps = app2 fmt.Println(reflect.TypeOf(app1)) fmt.Println(reflect.TypeOf(app1)) } 

2 Answers 2

1

You can't assign single element to array field so convert your

status.Apps = app1 status.Apps = app2 

to something like

status.Apps = []App{app1, app2} 

or

status.Apps = []App{} status.Apps = append(status.Apps, app1) status.Apps = append(status.Apps, app2) 

Also your JSON field named buildconfigs and in struct specification json:"builds". Structure's field always will be empty in this case.

Working example http://play.golang.org/p/fQ-XQsgK3j

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I think status.Apps = append(status.Apps, app1) works for my use case as I can invoke it in a loop.
1

Your question is a bit confusing to me :s But if you modify your JSON data to an JSON array and it will work with Unmarshal and could be unmarshal to status with no problems:

func main() { jsonData1 := []byte(` { "apps": [{ "appname": "php1", "buildconfigs":"deleted" },{ "appname": "php2", "buildconfigs":"exists" }] } `) var status Status json.Unmarshal(jsonData1, &status) fmt.Printf("%+v\n", status) } 

Working example here: http://play.golang.org/p/S4hOxJ6gHz

1 Comment

That is true. But I am getting the app information from another package. And I need to build the struct for status for multiple calls.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.