Home >Backend Development >Golang >How Can I Unmarshal a JSON Array with Mixed Data Types in Go?

How Can I Unmarshal a JSON Array with Mixed Data Types in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 05:00:09356browse

How Can I Unmarshal a JSON Array with Mixed Data Types in Go?

Unmarshalling an Array of Diverse Types

In JSON handling, unmarshalling arrays with varied element types can be challenging. This article addresses the issue of unmarshalling arrays consisting of elements with known but unsorted data types.

Go's Method for Arbitrary Data Decoding

As outlined in Go's official documentation on JSON encoding, it is possible to decode arbitrary data into an interface{} using the json.Unmarshal function. By using type assertion, the data type can be dynamically determined.

Adapting Your Code

The following modified version of your code showcases this approach:

package main

import (
    "encoding/json"
    "fmt"
)

var my_json string = `{
    "an_array":[
    "with_a string",
    {
        "and":"some_more",
        "different":["nested", "types"]
    }
    ]
}`

func IdentifyDataTypes(f interface{}) {
    switch vf := f.(type) {
    case map[string]interface{}:
        fmt.Println("is a map:")
        for k, v := range vf {
            switch vv := v.(type) {
            case string:
                fmt.Printf("%v: is string - %q\n", k, vv)
            case int:
                fmt.Printf("%v: is int - %q\n", k, vv)
            default:
                fmt.Printf("%v: ", k)
                IdentifyDataTypes(v)
            }

        }
    case []interface{}:
        fmt.Println("is an array:")
        for k, v := range vf {
            switch vv := v.(type) {
            case string:
                fmt.Printf("%v: is string - %q\n", k, vv)
            case int:
                fmt.Printf("%v: is int - %q\n", k, vv)
            default:
                fmt.Printf("%v: ", k)
                IdentifyDataTypes(v)
            }

        }
    }
}

func main() {

    fmt.Println("JSON:\n", my_json, "\n")

    var f interface{}
    err := json.Unmarshal([]byte(my_json), &f)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("JSON: ")
        IdentifyDataTypes(f)
    }
}

Output

The code produces the following output:

JSON:
 {
    "an_array":[
    "with_a string",
    {
        "and":"some_more",
        "different":["nested", "types"]
    }
    ]
}

JSON: is a map:
an_array: is an array:
0: is string - "with_a string"
1: is a map:
and: is string - "some_more"
different: is an array:
0: is string - "nested"
1: is string - "types"

This approach allows for dynamic identification and handling of element types within the array, providing a versatile solution for your unmarshalling needs.

The above is the detailed content of How Can I Unmarshal a JSON Array 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