How Can I Handle Dynamic JSON Field Types in Go?

Barbara Streisand
Release: 2024-11-19 03:16:02
Original
389 people have browsed it

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}
  ]
}
Copy after login
{
  "mykey": [
    "/obj1/is/at/this/path",
    "/obj2/is/at/this/other/path"
  ]
}
Copy after login

Go's Approach

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

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

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template