Home  >  Article  >  Backend Development  >  How to Unmarshal JSON Arrays with Mixed Data Types in Go?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 03:52:09721browse

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

Unmarshalling JSON Arrays with Mixed Data Types

The task of unmarshalling JSON arrays containing values of different data types can often pose a challenge. For instance, consider the following JSON array:

{["NewYork",123]}

Issue:

Firstly, it's crucial to note that the provided JSON is syntactically incorrect. JSON objects require keys for each value, so a correct representation would be either {"key":["NewYork",123]} or simply ["NewYork",123].

Furthermore, when dealing with JSON arrays comprised of multiple data types, the problem arises when Go arrays necessitate a specified type. This can leave you wondering how to handle such situations.

Solution:

The key to tackling this issue is to employ the type interface{}. It allows you to handle values of varied types without the need for explicit type conversion. Here's a code example that demonstrates how it works:

import (
    "encoding/json"
    "fmt"
)

const j = `{"NYC": ["NewYork",123]}`

type UntypedJson map[string][]interface{}

func main() {
    ut := UntypedJson{}
    fmt.Println(json.Unmarshal([]byte(j), &ut))
    fmt.Printf("%#v", ut)
}

In this example, we use UntypedJson as a custom type that maps strings to slices of interface{}. By utilizing the interface{} type, we can effortlessly handle mixed data types within the JSON array.

The output of the program would be:

<nil>
map[string][]interface{}{"NYC": \["NewYork" 123]}

Conclusion:

By leveraging the interface{} type, this approach enables you to effectively unmarshal JSON arrays with various data types.

The above is the detailed content of How to Unmarshal 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