Go language is a simple, efficient and reliable programming language, and it also provides many convenient libraries and tools when dealing with data. Among them, parsing JSON is a very common task. In this article, we will introduce in detail how to parse JSON in Go language, including the definition of JSON, methods of parsing, sample code and other aspects.
What is JSON?
JSON(JavaScript Object Notation) is a lightweight data exchange format used to pass data between different platforms and languages.JSON formatted data consists of key-value pairs separated by colons between keys and values, commas between key-value pairs, and curly braces wrapping the entire data. Example:
{
"name": "John",
"age": 20,
"address": {
"province": "Zhejiang",
"city": "Hangzhou"
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
JSON Parsing Methods in Go
The Go language providesencoding/json
package to support JSON parsing and generation. The package contains theMarshal
cap (a poem)Unmarshal
Two functions for converting Go structs to JSON format and for converting JSON-formatteddata conversionis a Go language struct.
Parsing JSON
We can use the function to parse data in JSON format. The function takes JSON formatted data as input and returns a Go language structure. The sample code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Address string
}
func main() {
jsonString := `{"name":"John","age":20,"address":"Hangzhou"}`
var p Person
err := json.Unmarshal([]byte(jsonString), &p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p.Name, p.Age, p.Address)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
In the above sample code, we define aPerson
structure and parses the JSON-formatted data into this structure. As you can see, we first define a string variablejsonString
which contains data in JSON format. Then, we define aPerson
variantp
and use function will
jsonString
resolve top
in. Finally, we can directly access thep
The fields in the
Generate JSON
We can use the function converts Go language structures to JSON formatted data. The function takes a Go language structure as input and returns a JSON formatted string. The sample code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Address string
}
func main() {
p := Person{
Name: "John",
Age: 20,
Address: "Hangzhou",
}
jsonString, err := json.Marshal(p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(jsonString))
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
In the above sample code, we define aPerson
structure and convert it to JSON format data. As you can see, we first define aPerson
variantp
and then use the function will
p
to a JSON-formatted string. Finally, we can use thestring
function converts a JSON formatted string to a normal string and outputs the result.
Advanced Usage of JSON Parsing
In addition to the basic JSON parsing methods, the Go language provides some advanced uses for working with JSON data.
Ignore fields that don't exist in JSON
In some cases, JSON data may contain fields that do not exist in Go language constructs. In this case, we can use the functional
json:"-"
tag to ignore these fields. The sample code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address string `json:"-"`
Email string `json:"email,omitempty"`
}
func main() {
jsonString := `{"name":"John","age":20,"address":"Hangzhou","phone":"1234567890"}`
var p Person
err := json.Unmarshal([]byte(jsonString), &p)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p.Name, p.Age, p.Address, p.Email)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
In the above sample code, we define aPerson
structure and use thejson:"-"
flag to ignore theAddress
fields. In addition, we use thejson:"email,omitempty"
flag to indicate when theEmail
The field is not output when it is empty. As you can see, when we parse the field containing thephone
field, the program does not report an error, and theAddress
The value of the field is the empty string.Email
field is not output.
utilization
typology
Sometimes the value of a field in JSON data is a string in JSON format. In this case, we can use the type to represent this field and parse it into a Go language structure if needed. The sample code is as follows:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address json.RawMessage `json:"address"`
}
type Address struct {
Province string `json:"province"`
City string `json:"city"`
}
func main() {
jsonString := `{"name":"John","age":20,"address":"{\"province\":\"Zhejiang\",\"city\":\"Hangzhou\"}"}`
var p Person
err := json.Unmarshal([]byte(jsonString), &p)
if err != nil {
fmt.Println(err)
return
}
var addr Address
err = json.Unmarshal(p.Address, &addr)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(p.Name, p.Age, addr.Province, addr.City)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
In the above sample code, we define aPerson
structure, whereAddress
The type of the field isWhen parsing JSON data, we first parse the JSON data into a single file. When parsing JSON data, we first parse the JSON data into a
Person
variantp
and then use the function will
resolve to an
Address
variantaddr
. Finally, we can directly access theaddr
The fields in the
summarize
This article describes in detail how to parse JSON in Go language, including the definition of JSON, parsing methods, sample code and other aspects. In the actual development, we often need to deal with JSON format data, mastering the JSON parsing method is very important.