In Go language, you can use the standard libraryencoding/json
InFunctions convert JSON strings to JSON data (usually a struct or map type in Go). Here is a simple example:
Sample code
package main import ( "encoding/json" "fmt" "log" ) // Define a structure to map JSON datatype Person struct { Name string `json:"name"` Age int `json:"age"` Hobbies []string `json:"hobbies"` } func main() { // JSON string jsonStr := `{ "name": "John", "age": 30, "hobbies": ["reading", "coding"] }` // Create a structure variable to store parsed data var person Person // Parses JSON strings into structures err := ([]byte(jsonStr), &person) if err != nil { ("Error unmarshalling JSON: %v", err) } // Print the parsed data ("Name: %s\n", ) ("Age: %d\n", ) ("Hobbies: %v\n", ) }
Code description
-
Define structure:
- use
struct
Define a Go structure corresponding to the JSON data structure. - use
json:"key"
Tags to specify the mapping relationship between keys in JSON and structure fields.
- use
-
Function:
-
(data []byte, v interface{}) error
:-
data
is a byte slice of a JSON string. -
v
It is a target variable used to store parsed data. - If the parsing is successful,
v
JSON data will be included; if it fails, an error will be returned.
-
-
-
Error handling:
- If the JSON format is erroneous or the structure field does not match,
An error will be returned.
- If the JSON format is erroneous or the structure field does not match,
Output result
After running the above code, the output is as follows:
Name: John
Age: 30
Hobbies: [reading coding]
Use map to parse JSON
If the JSON structure is not fixed, you can also use itmap[string]interface{}
To parse JSON data, the example is as follows:
package main import ( "encoding/json" "fmt" "log" ) func main() { jsonStr := `{ "name": "John", "age": 30, "hobbies": ["reading", "coding"] }` // Use map to store parsed data var data map[string]interface{} // parse JSON err := ([]byte(jsonStr), &data) if err != nil { ("Error unmarshalling JSON: %v", err) } // Access data in map ("Name: %v\n", data["name"]) ("Age: %v\n", data["age"]) ("Hobbies: %v\n", data["hobbies"]) }
This method is more flexible, but requires access to the value of the specific field through type assertions.
This is the end of this article about the implementation of converting json strings into json data in go language. For more related contents of converting go strings into json data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!