Home  >  Article  >  Backend Development  >  How Can I Handle Dynamic JSON Field Types in Go?

How Can I Handle Dynamic JSON Field Types in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 03:16:02381browse

How Can I Handle Dynamic JSON Field Types in Go?

Handling Dynamic JSON Field Types in Go

Deserializing JSON into structured data in Go can be challenging when the type of a key's value keeps changing. For instance, an API may provide data in varying formats, such as:

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

Go's Approach

To handle such dynamic JSON, consider using a flexible data structure like the following:

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

This structure allows for both strings and objects to be stored in the MyKey slice.

Distinguishing Types

Once the JSON is deserialized, you can differentiate between strings and objects using a type switch:

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 approach enables you to determine the type of each element in the MyKey slice and process it accordingly.

The above is the detailed content of How Can I Handle Dynamic JSON Field 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