How Can I Unmarshal Unknown JSON Formats in Go?

Susan Sarandon
Release: 2024-11-26 05:54:18
Original
368 people have browsed it

How Can I Unmarshal Unknown JSON Formats in Go?

Unmarshal JSON Data of Unknown Format

Introduction

Your JSON data follows an unknown format, presenting a challenge in unmarshalling it into a GoLang struct. This article will guide you through the steps to handle this scenario effectively.

Unmarshal with map[string]interface{}

Since you don't know the keys in advance, you can use map[string]interface{} to unmarshal your JSON payload. This allows you to store the key-value pairs as a map without specifying the types of the values.

var grades map[string]interface{}

err := json.Unmarshal([]byte(jsonString), &grades)
fmt.Println(err)

fmt.Printf("%#v\n", grades)
Copy after login

This will output the JSON data as a nested map of strings to interfaces, which can be useful for inspecting and processing the data dynamically.

Using json:"-" Tag

You can exclude certain fields from JSON marshaling/unmarshaling using the json:"-" tag. This can be useful if you want to keep some data private or avoid circular references.

type GradeData struct {
    Grades map[string]interface{} `json:"-"`
}

var gradesData GradeData
err := json.Unmarshal([]byte(jsonString), &gradesData.Grades)
fmt.Println(err)

fmt.Printf("%#v\n", gradesData)
Copy after login

In this example, the Grades field will not be included in the JSON representation of gradesData, but it can still be used to store and retrieve the JSON data.

Conclusion

By using map[string]interface{} and the json:"-" tag, you can successfully unmarshal JSON data of unknown format into GoLang structs. This approach allows you to handle dynamic and unknown JSON structures elegantly.

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