Rustam Rustam - 1 year ago 99
JSON Question

Decoding top level JSON array with json.Decoder in golang

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

Answer Source

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 in array of struct. This is a very simple example. Go Playground

package main

import (

type Result struct {
    Name         string `jaon:"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 {