How to convert JSON data to map type in golang
In Golang, since JSON is a common data exchange format, the need to convert JSON data into map is also very common. In this article, we will introduce how to convert JSON data to map type using Golang.
- Using the standard library unmarshal function
Golang’s standard library contains many JSON-related functions and types, the most important of which is the json.Unmarshal function. This function decodes JSON data into Go language data structures.
We can use this function to convert JSON string to map. First, define the variable used to store the JSON decoding results and create a byte array containing the JSON string. Then, call the json.Unmarshal function to decode the JSON string into a map type.
The following is an example:
package main import ( "encoding/json" "fmt" ) func main() { var data = []byte(`{"name":"Tom","age":28,"gender":"male"}`) var result map[string]interface{} err := json.Unmarshal(data, &result) if err != nil { fmt.Println("JSON转换失败:", err) return } for key, value := range result { fmt.Printf("%s : %v\n", key, value) } }
In the above code, we define a map type variable result to store the JSON decoding result. When calling json.Unmarshal to decode a JSON string, you need to pass the address of the result. Finally, we iterate over the key-value pairs in result and print them out. The output is as follows:
name : Tom age : 28 gender : male
- Use the third-party library easyjson
There is also a third-party JSON serialization library called easyjson in Golang, which can more conveniently Convert JSON to Go language data type. Unlike the standard library json.Unmarshal, easyjson uses code generation to improve parsing efficiency. Additionally, it supports more advanced features, such as parsing JSON into inline types or high-speed iteration.
To use easyjson, you need to install the library and include the code it generates in your Go code. First, install easyjson:
go get github.com/mailru/easyjson
Next, define an easyjson template for the data type that needs to be converted to JSON. The easyjson template consists of multiple files, each of which has a .go file and an _easyjson.go file.
The following is a sample code that uses the easyjson template to convert a JSON string into a map:
package main import ( "fmt" "github.com/mailru/easyjson/jlexer" "github.com/mailru/easyjson/jwriter" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Gender string `json:"gender"` } func main() { data := []byte(`{"name":"Tom","age":28,"gender":"male"}`) var result map[string]interface{} r := jlexer.Lexer{Data: data} result = parseMap(&r) for key, value := range result { fmt.Printf("%s : %v\n", key, value) } } func parseMap(r *jlexer.Lexer) map[string]interface{} { result := map[string]interface{}{} for { key := r.String() r.WantColon() switch r.PeekToken() { case '{': r.Discard() result[key] = parseMap(r) if r.PeekToken() == '}' { r.Discard() } case '[': r.Discard() result[key] = parseArray(r) if r.PeekToken() == ']' { r.Discard() } case jlexer.Int: result[key] = r.Int() case jlexer.String: result[key] = r.String() case jlexer.Null: result[key] = nil case jlexer.True: result[key] = true case jlexer.False: result[key] = false default: panic("unrecognizable JSON format") } if r.PeekToken() == ',' { r.Discard() } else { break } } return result } func parseArray(r *jlexer.Lexer) []interface{} { result := []interface{}{} for { switch r.PeekToken() { case '{': r.Discard() result = append(result, parseMap(r)) if r.PeekToken() == '}' { r.Discard() } case '[': r.Discard() result = append(result, parseArray(r)) if r.PeekToken() == ']' { r.Discard() } case jlexer.Int: result = append(result, r.Int()) case jlexer.String: result = append(result, r.String()) case jlexer.Null: result = append(result, nil) case jlexer.True: result = append(result, true) case jlexer.False: result = append(result, false) default: panic("unrecognizable JSON format") } if r.PeekToken() == ',' { r.Discard() } else { break } } return result }
In the above code, we define a structure named Person to represent the JSON string data in. We then create a JSON string in an easy-to-read format.
In the main function, we use jlexer.Lexer to pass JSON data to the parseMap function and store the result in the map type variable result. Finally, we print out the contents of the key-value pairs in the map.
In this example, we hand-write a function parseMap that decodes JSON strings. This function reads the JSONLexer and calls itself recursively to parse the JSON string. Finally, it returns a map object of the parsed results.
Using the decoder provided by easyjson can easily parse complex JSON structures, but when a large amount of data needs to be decoded into a map, the parsing efficiency may be reduced.
Conclusion
There are many ways to convert JSON data to map in Golang. The standard library provides json.Unmarshal, which can directly decode JSON data into a map. The third-party library easyjson provides a more efficient solution, but requires more setup and configuration.
Choose the appropriate solution based on the specific situation. If you only need to decode a simple JSON string, you can use the standard library; if you need to decode a large amount of data or a more complex structure, you can use the third-party library easyjson.
The above is the detailed content of How to convert JSON data to map type in golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
