"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Parse JSON Arrays in Go Using the `json` Package?

How to Parse JSON Arrays in Go Using the `json` Package?

Posted on 2025-03-26
Browse:829

How to Parse JSON Arrays in Go Using the `json` Package?

Parsing JSON Arrays in Go with the JSON Package

Problem: How can you parse a JSON string representing an array in Go using the json package?

Code Example:

Consider the following Go code:

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)
}

Explanation:

The provided code defines a type JsonType with an array of strings. It then attempts to unmarshal a JSON string into the array field of a JsonType instance. However, there is an issue with the code.

Solution:

The return value of Unmarshal is an error. The code originally printed this error instead of the unmarshaled array. To fix it, you can change the code to:

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

Additionally, you can simplify the code by directly unmarshaling into the array slice without using a custom type:

var arr []string
_ = json.Unmarshal([]byte(dataJson), &arr)

This code assigns the unmarshaled slice to arr. The underscore before the assignment suppresses the error value, which is not used in this code.

By using the json package effectively, you can easily parse JSON arrays in Go.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3