Master JSON Parsing in Go: map[string]interface{} vs Struct Tags & Libraries

This article explains how to handle JSON in Go, comparing the generic map[string]interface{} approach with strongly‑typed struct unmarshalling, demonstrating tag usage, and introducing third‑party libraries like SJSON and GJSON that simplify reading and writing JSON data.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master JSON Parsing in Go: map[string]interface{} vs Struct Tags & Libraries

My first Go project needed to process a collection of JSON test fixtures and pass the data as parameters to an API we built. Another team created these fixtures to provide language‑agnostic, predictable input and output for the API.

In strongly typed languages JSON handling is often difficult because JSON contains strings, numbers, objects and arrays. Languages such as JavaScript, Python, Ruby or PHP benefit from dynamic typing, so parsing and encoding JSON does not require explicit type handling.

// in PHP
$object = json_decode('{"foo":"bar"}');

// in JavaScript
const object = JSON.parse('{"foo":"bar"}');

In Go you must decide how to convert a JSON file into Go data structures. Below are two examples that illustrate common approaches.

Parsing/Serializing as map[string]interface{}

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    byt := []byte(`{
        "num":6.13,
        "strs":["a","b"],
        "obj":{"foo":{"bar":"zip","zap":6}}
    }`)
    var dat map[string]interface{}
    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
    num := dat["num"].(float64)
    fmt.Println(num)
    strs := dat["strs"].([]interface{})
    str1 := strs[0].(string)
    fmt.Println(str1)
    obj := dat["obj"].(map[string]interface{})
    obj2 := obj["foo"].(map[string]interface{})
    fmt.Println(obj2)
}

The JSON data is unmarshaled into a map[string]interface{} called dat. Accessing each value requires a type assertion, and handling deeply nested JSON quickly becomes cumbersome.

Parsing/Serializing as struct

package main

import (
    "encoding/json"
    "fmt"
)

type ourData struct {
    Num  float64                 `json:"num"`
    Strs []string                `json:"strs"`
    Obj  map[string]map[string]string `json:"obj"`
}

func main() {
    byt := []byte(`{
        "num":6.13,
        "strs":["a","b"],
        "obj":{"foo":{"bar":"zip","zap":6}}
    }`)
    var res ourData
    json.Unmarshal(byt, &res)
    fmt.Println(res.Num)
    fmt.Println(res.Strs)
    fmt.Println(res.Obj)
}

By defining a struct with JSON tags, the byte slice is unmarshaled directly into a concrete type ourData. The tags tell the encoding/json package which JSON fields map to which struct fields.

When json.Unmarshal deserializes a JSON object into this struct, the top‑level num field is assigned to ourData.Num .

This approach reduces the need for explicit type assertions, but it has limitations: tags only affect top‑level fields, nested JSON still requires nested types, and the struct assumes the JSON schema does not change. For example, the field zap is not captured by the struct above.

SJSON and GJSON

Go’s standard JSON handling remains unchanged, but third‑party packages such as SJSON (for writing) and GJSON (for reading) provide more concise and efficient APIs.

package main

import "github.com/tidwall/gjson"

const JSON = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
    value := gjson.Get(JSON, "name.last")
    println(value.String())
}
package main

import "github.com/tidwall/sjson"

const JSON = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`

func main() {
    value, _ := sjson.Set(JSON, "name.last", "Anderson")
    println(value)
}

If SJSON and GJSON do not suit your needs, many other third‑party libraries are available for more complex JSON manipulation in Go.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

parsingGostructgjsonmap[string]interface{}sjson
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.