"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Unmarshal JSON Arrays with Mixed Data Types in Go?

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

Published on 2024-12-22
Browse:983

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3