golang string to json

WBOY
Release: 2023-05-13 10:04:07
Original
3215 people have browsed it

In golang, to convert string type into json object, you can use the json package in the standard library.

First, we can use the json.Marshal() function to convert objects in golang into json format strings. For example:

type Person struct { Name string `json:"name"` Age int `json:"age"` } p := Person{Name: "Tom", Age: 29} jsonStr, err := json.Marshal(p) if err != nil { fmt.Println("json.Marshal failed:", err) } fmt.Println(string(jsonStr))
Copy after login

The above code will output the following results:

{"name":"Tom","age":29}
Copy after login

Next, we can use the json.Unmarshal() function to convert the json string into an object in golang. For example:

jsonStr := `{"name":"Tom","age":29}` var p Person err := json.Unmarshal([]byte(jsonStr), &p) if err != nil { fmt.Println("json.Unmarshal failed:", err) } fmt.Println(p.Name, p.Age)
Copy after login

The above code will output the following results:

Tom 29
Copy after login

It should be noted that when parsing json, parameters of type []byte are used, so the mandatory type is required Conversion converts string type to []byte type.

In addition, you can also directly use the json.NewDecoder() function to parse the json format string into a json object, for example:

jsonStr := `{"name":"Tom","age":29}` var data interface{} decoder := json.NewDecoder(strings.NewReader(jsonStr)) err := decoder.Decode(&data) if err != nil { fmt.Println("json.Unmarshal failed:", err) } fmt.Println(data)
Copy after login

The above code will output the following results:

map[name:Tom age:29]
Copy after login

In this way, we can use the standard library json package in golang to convert the string type into a json object.

The above is the detailed content of golang string to json. 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!