Home >Backend Development >Golang >How to Parse JSON Arrays in Go using the `encoding/json` Package?

How to Parse JSON Arrays in Go using the `encoding/json` Package?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 22:59:121015browse

How to Parse JSON Arrays in Go using the `encoding/json` Package?

Parsing JSON Arrays in Go Using the JSON Package

Question

How can I parse a string that represents a JSON array in Go using the encoding/json package?

type JsonType struct {
    Array []string
}

func main() {
    dataJson := `["1","2","3"]`
    arr := JsonType{}
    unmarshaled := json.Unmarshal([]byte(dataJson), &arr.Array)
    log.Printf("Unmarshaled: %v", unmarshaled)
}

Answer

The provided code returns the error value from Unmarshal. To correctly parse the JSON array, use the following code:

err := json.Unmarshal([]byte(dataJson), &arr)

Additionally, you can simplify the code by using a slice instead of a custom struct:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    dataJson := `["1","2","3"]`
    var arr []string
    err := json.Unmarshal([]byte(dataJson), &arr)
    fmt.Println(err)
    fmt.Println(arr)
}

This code will output:

<nil>
[1 2 3]

Background

Passing a pointer to Unmarshal enables the function to reduce or eliminate memory allocations. Additionally, in a processing context, the caller may reuse the same value repeatedly, further saving allocations.

The above is the detailed content of How to Parse JSON Arrays in Go using the `encoding/json` Package?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn