In the Go language, encoding and decoding data using JSON is a very common operation. But in some cases, we may need to convert JSON data into a map to facilitate other operations on it. In this article, we will introduce how to convert JSON data to map type using Go language.
The encoding/json package is provided in the Go language, which provides encoding and decoding functions for JSON data. Use this package to decode JSON data into structures or primitive types in the Go language. But if we want to convert JSON data to map type, we need to process it manually.
Suppose we have the following JSON data:
{ "name": "John", "age": 22, "gender": "male", "friends": [ { "name": "Marry", "age": 20 }, { "name": "Tom", "age": 23 } ] }
The following is the code to convert the JSON data to map type:
package main import ( "encoding/json" "fmt" ) func jsonToMap(jsonStr string) (map[string]interface{}, error) { var result map[string]interface{} err := json.Unmarshal([]byte(jsonStr), &result) if err != nil { return nil, err } return result, nil } func main() { jsonStr := `{ "name": "John", "age": 22, "gender": "male", "friends": [ { "name": "Marry", "age": 20 }, { "name": "Tom", "age": 23 } ] }` result, err := jsonToMap(jsonStr) if err != nil { fmt.Println(err) return } fmt.Println(result) }
A function jsonToMap is defined in the code, which The function receives a JSON string as a parameter and returns a result of type map[string]interface{}. In the function, we use json.Unmarshal method to decode the JSON string into map type. In the decoded map[string]interface{} object, the key corresponds to the string in the JSON data, and the value type is the same as the corresponding JSON data type. Since the data type in JSON is not limited, after decoding, we define the value type of the result as the interface{} type.
In the main function, we pass the JSON string to the jsonToMap function and print out the return result. Running the program, we can get the following output:
map[name:John age:22 friends:[map[age:20 name:Marry] map[age:23 name:Tom]] gender:male]
As you can see, after converting JSON to map, we can operate on it as we like. For example, we can get the corresponding value through the key, such as result["name"] to get the string John. In addition, when the JSON data is complex, we can also use the method of converting map to struct to facilitate data operations and type conversion.
Summary
This article details the method of converting JSON data into map in Go language. We used the Unmarshal method in the encoding/json package to decode the JSON string into a map type, and explained some of the points that need attention. Through studying this article, we should have a deeper understanding of the problems caused by using JSON to process data, and be able to process data more efficiently.
The above is the detailed content of golang json to map. For more information, please follow other related articles on the PHP Chinese website!

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
