How do I parse a JSON array in Go?

Linda Hamilton
Release: 2024-11-19 20:23:03
Original
479 people have browsed it

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

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

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

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

Output:

Galaxy Nexus 3460.00
Galaxy Nexus 3460.00
Copy after login

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!

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