How does golang parse json strings in unknown format (possibly json objects, possibly json arrays)

  golang, question

First, parse json array string

data:= `[
 {
 "name": "aaa",
 "id":   "54546221"
 },
 {
 "name": "bbb",
 "id":   "89875646"
 }
 ]`
 `
 
 dataArr := []interface{}{}
 err := json.Unmarshal([]byte(data), &dataArr)

Second, parsing json object strings

data:= `{
 "name": "aaa",
 "id":   "54546221"
 }`
 `
 dataArr := map[string]interface{}{}
 err := json.Unmarshal([]byte(data), &dataArr)

How to parse a data string without knowing the data json format?

package main
 
 import (
 "log"
 
 "github.com/bitly/go-simplejson"
 )
 
 func main() {
 data := "[1,2,3,4]"
 parsed, err := simplejson.NewJson([]byte(data))
 if err !  = nil {
 log.Panic(err)
 }
 log.Println(parsed.GetIndex(2).MustInt())
 }

This is an already implemented library that can parse JSON strings into oneJSONThe object of.
The principle is also very simple,Unmarshaltointerface{}Just do it

package main
 
 import (
 "encoding/json"
 "log"
 )
 
 func main() {
 data := `{"a":[1,2,3,4]}`
 // data := `[1,2,3,4]`
 var target interface{}
 if err := json.Unmarshal([]byte(data), &target);   err !  = nil {
 log.Panic(err)
 }
 //It is necessary to judge his type here.
 retArray, ok := target.([]interface{})
 if ok {
 log.Println(retArray)
 } else {
 retMap, _ := target.(map[string]interface{})
 log.Println(retMap)
 }
 }