Home >Backend Development >Golang >How to Decode JSON Arrays with Mixed Data Types in Go?

How to Decode JSON Arrays with Mixed Data Types in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-23 04:33:16949browse

How to Decode JSON Arrays with Mixed Data Types in Go?

Decoding JSON Arrays with Mixed Value Types

In some cases, you may encounter JSON arrays that contain elements of different types. For instance:

{["NewYork",123]}

Go arrays require you to explicitly specify their type, which can become challenging when dealing with arrays of mixed types.

Solution Using Interface{}

To handle mixed-type arrays, you can leverage the interface{} type, which allows values of any type. Here's how you can achieve this in Go:

package main

import (
    "encoding/json"
    "fmt"
)

type UntypedJson map[string][]interface{}

func main() {
    j := `{"NYC": ["NewYork",123]}`
    ut := UntypedJson{}
    err := json.Unmarshal([]byte(j), &ut)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("%#v", ut)
}
  • First, we define a custom type UntypedJson that maps strings to arrays of interface{}. This allows us to store values of any type in the array.
  • We use json.Unmarshal to decode the JSON string into our UtnyptedJson type. Since interface{} can hold any type, it can handle both string and integer elements in the array.
  • Finally, we use fmt.Printf to display the unmarshaled data.

Note: It's worth noting that the provided JSON example is technically invalid, as JSON objects must have keys. A corrected example would be:

{"NYC": ["NewYork",123]}

The above is the detailed content of How to Decode JSON Arrays with Mixed Data Types 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