Home  >  Article  >  Backend Development  >  How do I parse a JSON array in Go?

How do I parse a JSON array in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 20:23:03465browse

How do I parse a JSON array in Go?

How to Parse JSON Array in Go

In Go, the encoding/json package provides support for unmarshalling JSON data into Go structures. To parse a JSON array, you can use the following steps:

  1. Define a Go struct: Define a struct that represents the shape of the individual elements in the JSON array. For example, if the JSON array contains objects with name and price fields, you would define the following struct:

    type PublicKey struct {
        Name string
        Price string
    }

    Note: Ensure that the field names in the struct match the field names in the JSON array.

  2. Create a slice of the struct: Create a slice of the defined struct type to hold the parsed data:

    var keys []PublicKey
  3. Unmarshal the JSON: Use the json.Unmarshal() function to unmarshal the JSON array into the slice of structs:

    err := json.Unmarshal([]byte(jsonStr), &keys)

    where jsonStr is the JSON data to be parsed.

  4. Handle any errors: Check for any errors encountered during unmarshalling. If an error occurs, it will be stored in the err variable:

    if err != nil {
        // Handle the error
    }
  5. Access the parsed data: Once the JSON array is parsed, you can access the individual elements of the slice of structs:

    for _, key := range keys {
        fmt.Println(key.Name, key.Price)
    }

Example:

The following code demonstrates how to parse a JSON array using the above steps:

package main

import (
    "encoding/json"
    "fmt"
)

type PublicKey struct {
    Name string
    Price string
}

func main() {
    jsonStr := `[{"name":"Galaxy Nexus", "price":"3460.00"},{"name":"Galaxy Nexus", "price":"3460.00"}]`

    var keys []PublicKey
    err := json.Unmarshal([]byte(jsonStr), &keys)
    if err == nil {
        for _, key := range keys {
            fmt.Println(key.Name, key.Price)
        }
    } else {
        fmt.Println(err)
    }
}

Output:

Galaxy Nexus 3460.00
Galaxy Nexus 3460.00

The above is the detailed content of How do I parse a JSON array in Go?. 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