Skip to content

Crack SDE

Most of the content are generated by AI, with human being reviewed, edited, and revised

Menu
  • Home
  • Daily English Story
  • Tech Interviews
  • Cloud Native
  • DevOps
  • Artificial Intelligence
Menu

Decode JSON in Golang

Posted on 10/10/202311/14/2023 by user

In Go (Golang), there are several ways to decode JSON, each suited for different scenarios. Here’s a list of common methods along with their typical use cases:

1. json.Unmarshal

json.Unmarshal: This is the most straightforward method when you have the entire JSON data available as a byte slice. It’s best used when the JSON data is not too large and can be comfortably loaded into memory.

package main

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

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    jsonData := []byte(`{"name":"John Doe","age":30,"email":"johndoe@example.com"}`)

    var person Person
    err := json.Unmarshal(jsonData, &person)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v\n", person)
}

2. json.NewDecoder with io.Reader

json.NewDecoder with io.Reader: As already discussed, json.Decoder is ideal for processing JSON data from streams. This is particularly useful when dealing with large JSON files or network streams.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    jsonData := `{"name":"John Doe","age":30,"email":"johndoe@example.com"}`
    reader := strings.NewReader(jsonData)

    var person Person
    err := json.NewDecoder(reader).Decode(&person)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v\n", person)
}

3. Streaming with json.Decoder

Streaming with json.Decoder: If your JSON contains an array of objects and you want to process each object as it’s read, json.Decoder can be used in a streaming fashion. This approach is memory-efficient for large arrays.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "strings"
)

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    jsonData := `[{"name":"John Doe","age":30,"email":"johndoe@example.com"}, {"name":"Jane Doe","age":28,"email":"janedoe@example.com"}]`
    reader := strings.NewReader(jsonData)

    decoder := json.NewDecoder(reader)
    // Read opening bracket of the array
    _, err := decoder.Token()
    if err != nil {
        log.Fatal(err)
    }

    // While the array contains values
    for decoder.More() {
        var person Person
        err := decoder.Decode(&person)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%+v\n", person)
    }
}

4. json.RawMessage

json.RawMessage: When you need to delay JSON decoding, or only conditionally decode parts of the JSON, json.RawMessage can be used. It allows you to unmarshal a JSON object into a raw byte slice, which can be unmarshalled later.

package main

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

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    jsonData := []byte(`{"name":"John Doe","age":30,"email":"johndoe@example.com"}`)

    var raw json.RawMessage = jsonData

    var person Person
    err := json.Unmarshal(raw, &person)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%+v\n", person)
}

5. Using map[string]interface{} or interface{}

map[string]interface{} or interface{}: For very dynamic JSON structures where you don’t have a predetermined struct, you can unmarshal JSON into a map[string]interface{} or an empty interface{}. This method requires type assertion for accessing nested data.

package main

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

func main() {
    jsonData := []byte(`{"name":"John Doe","age":30,"email":"johndoe@example.com"}`)

    var data map[string]interface{}
    err := json.Unmarshal(jsonData, &data)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(data)
}

Each of these examples demonstrates a different method of working with JSON in Go, tailored to various use cases and data structures.

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related

10

Recent Posts

  • LC#622 Design Circular Queue
  • Started with OpenTelemetry in Go
  • How Prometheus scrap works, and how to find the target node and get the metrics files
  • How to collect metrics of container, pods, node and cluster in k8s?
  • LC#200 island problem

Recent Comments

  1. another user on A Journey of Resilience

Archives

  • May 2025
  • April 2025
  • February 2025
  • July 2024
  • April 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023

Categories

  • Artificial Intelligence
  • Cloud Computing
  • Cloud Native
  • Daily English Story
  • Database
  • DevOps
  • Golang
  • Java
  • Leetcode
  • Startups
  • Tech Interviews
©2025 Crack SDE | Design: Newspaperly WordPress Theme
Manage Cookie Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Manage options Manage services Manage {vendor_count} vendors Read more about these purposes
View preferences
{title} {title} {title}