5

Is it possible to decode top level JSON array with json.Decoder?

Or reading entire JSON and json.Unmarshall is the only way in this case?

I have read the accepted answer in this question and cannot figure out how to use it with top level JSON array

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rustam
  • 150
  • 2
  • 10

2 Answers2

8

You use json.Decoder in same way as any other json. Only difference is that instead of decoding into a struct, json need to be decoded into a slice of struct. This is a very simple example. Go Playground

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type Result struct {
    Name         string `json:"Name"`
    Age          int    `json:"Age`
    OriginalName string `json:"Original_Name"`
}

func main() {
    jsonString := `[{"Name":"Jame","Age":6,"Original_Name":"Jameson"}]`
    result := make([]Result, 0)
    decoder := json.NewDecoder(bytes.NewBufferString(jsonString))
    err := decoder.Decode(&result)
    if err != nil {
        panic(err)
    }
    fmt.Println(result)
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mayank Patel
  • 8,088
  • 5
  • 55
  • 75
1

https://play.golang.org/p/y2sKN7e8gf

Note that use of var r interface{} is not recommended, you should define your JSON structure as a Go struct to parse it correctly.

huygn
  • 980
  • 1
  • 13
  • 22