John Difool John Difool - 2 years ago 88
JSON Question

Runtime error while parsing a JSON byte stream with an embedded array

I am able to parse a simple JSON object into a struct, but when I try to parse an array inside that object, I am getting an

index out of range

package main

import (

type jsonobject struct {
Objects []ObjectType `json:"objects"`

type ObjectType struct {
Name string `json:"name"`

func main() {

// Simple element
bytes := []byte(`{ "name": "foo" }`)
var objecttype ObjectType
json.Unmarshal(bytes, &objecttype)
fmt.Printf("Results: %v\n", objecttype.Name) // Results: localhost

// Object with embedded array
bytes = []byte(`{ "objects": [ "name": "foo" ] }`)
jsontype := &jsonobject{}
json.Unmarshal(bytes, &jsontype)
fmt.Printf("Results: %v\n", jsontype.Objects[0].Name) // panic: runtime error: index out of range

Answer Source

Because your JSON input is not what you model in Go. And so the JSON array will not be unmarshaled into jsonobject.Objects: it will remain nil; so attempting to index it will result in index out of range error.

Try to unmarshal from this:

bytes = []byte(`{ "objects": [ {"name": "foo"} ] }`)

Note that the elements (one element in this case) in the JSON array are also in braces (JSON object).

Try it on the Go Playground.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download