Home >Backend Development >Golang >How Can I Handle JSON Unmarshaling with Variable Data Types (Objects or Strings) in Go?

How Can I Handle JSON Unmarshaling with Variable Data Types (Objects or Strings) in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 00:51:15226browse

How Can I Handle JSON Unmarshaling with Variable Data Types (Objects or Strings) in Go?

Handling JSON Unmarshaling with Arrays of Objects or Strings in Go

When unmarshaling JSON into structs in Go, you may encounter fields that can contain varying types (objects or strings) from request to request. For example, a field named "mykey" could sometimes hold inline objects and other times contain references to objects at specific paths.

Go-Idiomatic Solution

An idiomatic Go approach to handle this situation is to define a struct with a field whose type is a slice of interface{} values. This allows the field to hold both objects and strings, as Go will automatically decode them into the appropriate type based on the incoming JSON. The following code demonstrates this:

type Data struct {
    MyKey []interface{} `json:"mykey"`
}

Type Checking

After unmarshaling the JSON, you can use a type switch to distinguish between objects and strings in the slice:

for i, v := range data.MyKey {
    switch x := v.(type) {
    case string:
        fmt.Println("Got a string: ", x)
    case map[string]interface{}:
        fmt.Printf("Got an object: %#v\n", x)
    }
}

This allows you to handle both types of values in a structured and efficient manner.

Example

Consider the following JSON:

{
  "mykey": [
    {obj1}, 
    {obj2}
  ]
}

After unmarshaling this JSON into a Data struct, the MyKey slice will contain two elements, each of type map[string]interface{}.

Alternatively, if the JSON contained references to objects:

{
  "mykey": [
    "/obj1/is/at/this/path", 
    "/obj2/is/at/this/other/path"
  ]
}

The MyKey slice will contain two elements, each of type string.

The above is the detailed content of How Can I Handle JSON Unmarshaling with Variable Data Types (Objects or Strings) 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