Home >Backend Development >Golang >How to Parse JSON Arrays into Structured Data in Go?

How to Parse JSON Arrays into Structured Data in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 19:31:02571browse

How to Parse JSON Arrays into Structured Data in Go?

Parsing JSON Arrays in Go

Using Unmarshal with Defined Struct

Problem:

How to parse a complex JSON array containing objects into a structured format in Go?

Sample JSON:

[{"id":694476444991229955,"id_str":"694476444991229955"}]

Solution:

  1. Define a Go struct to model the JSON data.

    type Tweet struct {
     ID       int64  `json:"id"`
     IDStr    string `json:"id_str"`
    }
  2. Create a slice of the tweet struct to hold the parsed results.

    tweets := make([]Tweet, 0)
  3. Unmarshal the JSON array into the tweet slice.

    err := json.Unmarshal([]byte(jsonString), &tweets)
    if err != nil {
     fmt.Println(err)
    }
  4. Iterate over the tweet slice to access the parsed data.

    for _, tweet := range tweets {
     fmt.Println(tweet.ID, tweet.IDStr)
    }

Unmarshaling into Map[string]interface{} slice

Note: This method requires indexing and type assertion to access the values.

  1. Create a slice of maps to hold the parsed results.

    tweets := make([]map[string]interface{}, 0)
  2. Unmarshal the JSON array into the map slice.

    err := json.Unmarshal([]byte(jsonString), &tweets)
    if err != nil {
     fmt.Println(err)
    }
  3. Iterate over the map slice to access the parsed data.

    for _, tweet := range tweets {
     id, ok := tweet["id"].(int64)
     if ok {
         fmt.Println("ID:", id)
     }
    }

The above is the detailed content of How to Parse JSON Arrays into Structured Data 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