0.00

JSON decode in Go Lang

Sample method and data structure to decode from JSON in go


programming language: go lang 1.11 or later
operating system: any
Updated:


Method definition: JSON decode to a generic map[string] structure

// lib.go

package main

import (
    "errors"
    "strings"
    "encoding/json"
)

func JsonObjDecode(data string) (ds map[string]interface{}, er error) { // can decode any JSON Object as {"key1":..., "key2":...}
    //-- no need any panic handler
    if data == "" {
        return nil, errors.New("Empty Data Provided")
    } //end if
    //--
    var dat map[string]interface{}
    dataReader := strings.NewReader(data)
    decoder := json.NewDecoder(dataReader)
    decoder.UseNumber()
    err := decoder.Decode(&dat)
    if err != nil {
        return nil, err
    } //end if
    //--
    return dat, nil
    //--
} //END FUNCTION



Sample usage

// app.go
// go build app.go lib.go

package main

import (
    "log"
)

func main() {

    json := `{"id":1,"type":1001,"name":"Sample","value":10.01,"status":true}`

    data, err := JsonObjDecode(json)
    if err != nil {
        log.Fatal(err)
    }

    log.Println(data)
}