Remove 07.2.md spaces
This commit is contained in:
92
en/07.2.md
92
en/07.2.md
@@ -8,7 +8,7 @@ Since JSON is becoming more and more important in web development, let's take a
|
||||
|
||||
Here we use JSON to represent the example in the previous section:
|
||||
```json
|
||||
{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}
|
||||
{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}
|
||||
```
|
||||
The rest of this section will use this JSON data to introduce JSON concepts in Go.
|
||||
|
||||
@@ -18,33 +18,33 @@ The rest of this section will use this JSON data to introduce JSON concepts in G
|
||||
|
||||
Suppose we have the JSON in the above example. How can we parse this data and map it to a struct in Go? Go provides the following function for just this purpose:
|
||||
```Go
|
||||
func Unmarshal(data []byte, v interface{}) error
|
||||
func Unmarshal(data []byte, v interface{}) error
|
||||
```
|
||||
We can use this function like so:
|
||||
|
||||
```Go
|
||||
package main
|
||||
package main
|
||||
|
||||
import (
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
type Server struct {
|
||||
ServerName string
|
||||
ServerIP string
|
||||
}
|
||||
}
|
||||
|
||||
type Serverslice struct {
|
||||
type Serverslice struct {
|
||||
Servers []Server
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
func main() {
|
||||
var s Serverslice
|
||||
str := `{"servers":[{"serverName":"Shanghai_VPN","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
|
||||
json.Unmarshal([]byte(str), &s)
|
||||
fmt.Println(s)
|
||||
}
|
||||
}
|
||||
```
|
||||
In the above example, we defined a corresponding structs in Go for our JSON, using slice for an array of JSON objects and field name as our JSON keys. But how does Go know which JSON object corresponds to which specific struct filed? Suppose we have a key called `Foo` in JSON. How do we find its corresponding field?
|
||||
|
||||
@@ -67,31 +67,31 @@ We know that an interface{} can be anything in Go, so it is the best container t
|
||||
|
||||
Suppose we have the following JSON data:
|
||||
```Go
|
||||
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
|
||||
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
|
||||
```
|
||||
Now we parse this JSON to an interface{}:
|
||||
```Go
|
||||
var f interface{}
|
||||
err := json.Unmarshal(b, &f)
|
||||
var f interface{}
|
||||
err := json.Unmarshal(b, &f)
|
||||
```
|
||||
The `f` stores a map, where keys are strings and values are interface{}'s'.
|
||||
```Go
|
||||
f = map[string]interface{}{
|
||||
f = map[string]interface{}{
|
||||
"Name": "Wednesday",
|
||||
"Age": 6,
|
||||
"Parents": []interface{}{
|
||||
"Gomez",
|
||||
"Morticia",
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
So, how do we access this data? Type assertion.
|
||||
```Go
|
||||
m := f.(map[string]interface{})
|
||||
m := f.(map[string]interface{})
|
||||
```
|
||||
After asserted, you can use the following code to access data:
|
||||
```Go
|
||||
for k, v := range m {
|
||||
for k, v := range m {
|
||||
switch vv := v.(type) {
|
||||
case string:
|
||||
fmt.Println(k, "is string", vv)
|
||||
@@ -107,13 +107,13 @@ After asserted, you can use the following code to access data:
|
||||
default:
|
||||
fmt.Println(k, "is of a type I don't know how to handle")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
As you can see, we can now parse JSON of an unknown format through interface{} and type assertion.
|
||||
|
||||
The above example is the official solution, but type asserting is not always convenient. So, I recommend an open source project called `simplejson`, created and maintained by bitly. Here is an example of how to use this project to deal with JSON of an unknown format:
|
||||
```Go
|
||||
js, err := NewJson([]byte(`{
|
||||
js, err := NewJson([]byte(`{
|
||||
"test": {
|
||||
"array": [1, "2", 3],
|
||||
"int": 10,
|
||||
@@ -122,11 +122,11 @@ The above example is the official solution, but type asserting is not always con
|
||||
"string": "simplejson",
|
||||
"bool": true
|
||||
}
|
||||
}`))
|
||||
}`))
|
||||
|
||||
arr, _ := js.Get("test").Get("array").Array()
|
||||
i, _ := js.Get("test").Get("int").Int()
|
||||
ms := js.Get("test").Get("string").MustString()
|
||||
arr, _ := js.Get("test").Get("array").Array()
|
||||
i, _ := js.Get("test").Get("int").Int()
|
||||
ms := js.Get("test").Get("string").MustString()
|
||||
```
|
||||
It's not hard to see how convenient this is. Check out the repository to see more information: [https://github.com/bitly/go-simplejson](https://github.com/bitly/go-simplejson).
|
||||
|
||||
@@ -134,27 +134,27 @@ It's not hard to see how convenient this is. Check out the repository to see mor
|
||||
|
||||
In many situations, we need to produce JSON data and respond to clients. In Go, the JSON package has a function called `Marshal` to do just that:
|
||||
```Go
|
||||
func Marshal(v interface{}) ([]byte, error)
|
||||
func Marshal(v interface{}) ([]byte, error)
|
||||
```
|
||||
Suppose we need to produce a server information list. We have following sample:
|
||||
```Go
|
||||
package main
|
||||
package main
|
||||
|
||||
import (
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
)
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
type Server struct {
|
||||
ServerName string
|
||||
ServerIP string
|
||||
}
|
||||
}
|
||||
|
||||
type Serverslice struct {
|
||||
type Serverslice struct {
|
||||
Servers []Server
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
func main() {
|
||||
var s Serverslice
|
||||
s.Servers = append(s.Servers, Server{ServerName: "Shanghai_VPN", ServerIP: "127.0.0.1"})
|
||||
s.Servers = append(s.Servers, Server{ServerName: "Beijing_VPN", ServerIP: "127.0.0.2"})
|
||||
@@ -163,22 +163,22 @@ Suppose we need to produce a server information list. We have following sample:
|
||||
fmt.Println("json err:", err)
|
||||
}
|
||||
fmt.Println(string(b))
|
||||
}
|
||||
}
|
||||
```
|
||||
Output:
|
||||
```json
|
||||
{"Servers":[{"ServerName":"Shanghai_VPN","ServerIP":"127.0.0.1"},{"ServerName":"Beijing_VPN","ServerIP":"127.0.0.2"}]}
|
||||
{"Servers":[{"ServerName":"Shanghai_VPN","ServerIP":"127.0.0.1"},{"ServerName":"Beijing_VPN","ServerIP":"127.0.0.2"}]}
|
||||
```
|
||||
As you know, all field names are capitalized, but if you want your JSON key names to start with a lower case letter, you should use `struct tag`s. Otherwise, Go will not produce data for internal fields.
|
||||
```Go
|
||||
type Server struct {
|
||||
type Server struct {
|
||||
ServerName string `json:"serverName"`
|
||||
ServerIP string `json:"serverIP"`
|
||||
}
|
||||
}
|
||||
|
||||
type Serverslice struct {
|
||||
type Serverslice struct {
|
||||
Servers []Server `json:"servers"`
|
||||
}
|
||||
}
|
||||
```
|
||||
After this modification, we can produce the same JSON data as before.
|
||||
|
||||
@@ -191,7 +191,7 @@ Here are some points you need to keep in mind when trying to produce JSON:
|
||||
|
||||
Example:
|
||||
```Go
|
||||
type Server struct {
|
||||
type Server struct {
|
||||
// ID will not be outputed.
|
||||
ID int `json:"-"`
|
||||
|
||||
@@ -201,20 +201,20 @@ Example:
|
||||
|
||||
// If ServerIP is empty, it will not be outputted.
|
||||
ServerIP string `json:"serverIP,omitempty"`
|
||||
}
|
||||
}
|
||||
|
||||
s := Server {
|
||||
s := Server {
|
||||
ID: 3,
|
||||
ServerName: `Go "1.0" `,
|
||||
ServerName2: `Go "1.0" `,
|
||||
ServerIP: ``,
|
||||
}
|
||||
b, _ := json.Marshal(s)
|
||||
os.Stdout.Write(b)
|
||||
}
|
||||
b, _ := json.Marshal(s)
|
||||
os.Stdout.Write(b)
|
||||
```
|
||||
Output:
|
||||
```json
|
||||
{"serverName":"Go \"1.0\" ","serverName2":"\"Go \\\"1.0\\\" \""}
|
||||
{"serverName":"Go \"1.0\" ","serverName2":"\"Go \\\"1.0\\\" \""}
|
||||
```
|
||||
The `Marshal` function only returns data when it has succeeded, so here are some points we need to keep in mind:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user