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!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
