How to convert JSON data to map type in golang

PHPz
Release: 2023-04-21 14:46:51
Original
5336 people have browsed it

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.

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

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
Copy after login
  1. 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
Copy after login

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

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!

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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!