-2

I have the following JSON structure:

dataJson := `{"data1" : [["a",1]["b",2]], "data2": ["a","b",3]}`

And want to unmarshal it with Go. I am trying the following code:

type myData struct {
    row    map[string][][]interface{} `json:"data1"`
    column map[string][]interface{}   `json:"data2"`
}

var arr myData

_ = json.Unmarshal([]byte(dataJson), &arr)

But I get empty data:

Unmarshaled: {map[] map[]}

Any idea how to parse such JSON structure?

icza
  • 389,944
  • 63
  • 907
  • 827
jsor
  • 97
  • 5

1 Answers1

1

First problem is that struct fields must be exported (start their name with uppercased letters). See Why struct fields are showing empty? for more details.

Next, your input JSON is invalid, you have a missing comma between elements of data1 array. It should be:

{"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}

Third, data1 and data2 are JSON arrays, so you have to use a slice in Go and not a map.

Something like this:

type myData struct {
    Row    [][]interface{} `json:"data1"`
    Column []interface{}   `json:"data2"`
}

json.Unmarshal() returns an error, never omit errors in Go. The least you can do is print them so you'll know something's not right:

dataJson := `{"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}`

var arr myData
if err := json.Unmarshal([]byte(dataJson), &arr); err != nil {
    log.Println(err)
}
log.Printf("Unmarshaled: %v", arr)

This outputs (try it on the Go Playground):

2009/11/10 23:00:00 Unmarshaled: {[[a 1] [b 2]] [a b 3]}
icza
  • 389,944
  • 63
  • 907
  • 827