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
Release: 2024-11-17 19:31:02
Original
547 people have browsed it

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

Solution:

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

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

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

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

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

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)
    Copy after login
  2. Unmarshal the JSON array into the map slice.

    err := json.Unmarshal([]byte(jsonString), &tweets)
    if err != nil {
     fmt.Println(err)
    }
    Copy after login
    Copy after login
  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)
     }
    }
    Copy after login

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!

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