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
Release: 2024-11-30 22:59:12
Original
954 people have browsed it

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)
}
Copy after login

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)
Copy after login

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)
}
Copy after login

This code will output:

<nil>
[1 2 3]
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template