This commit is contained in:
badkaktus 2019-10-09 21:58:24 +03:00
parent e69f56644e
commit 1660a57d5f
2 changed files with 50 additions and 49 deletions

View File

@ -1,6 +1,6 @@
// Go offers built-in support for JSON encoding and // Go предлагает встроенную поддержку кодирования и
// decoding, including to and from built-in and custom // декодирования JSON, в том числе встроенных и
// data types. // пользовательских типов данных.
package main package main
@ -10,15 +10,16 @@ import (
"os" "os"
) )
// We'll use these two structs to demonstrate encoding and // Мы будем использовать эти две структуры, для демонстрации
// decoding of custom types below. // кодирования и декодирования.
type response1 struct { type response1 struct {
Page int Page int
Fruits []string Fruits []string
} }
// Only exported fields will be encoded/decoded in JSON. // Только экспортируемые поля могут быть кодированы и
// Fields must start with capital letters to be exported. // декодированы в JSON. Поля должны начинаться с
// заглавной буквы.
type response2 struct { type response2 struct {
Page int `json:"page"` Page int `json:"page"`
Fruits []string `json:"fruits"` Fruits []string `json:"fruits"`
@ -26,9 +27,9 @@ type response2 struct {
func main() { func main() {
// First we'll look at encoding basic data types to // Для начала мы рассмотрим кодирование данных в
// JSON strings. Here are some examples for atomic // JSON строку. Вот несколько примеров для простых
// values. // типов данных.
bolB, _ := json.Marshal(true) bolB, _ := json.Marshal(true)
fmt.Println(string(bolB)) fmt.Println(string(bolB))
@ -41,8 +42,8 @@ func main() {
strB, _ := json.Marshal("gopher") strB, _ := json.Marshal("gopher")
fmt.Println(string(strB)) fmt.Println(string(strB))
// And here are some for slices and maps, which encode // А вот примеры для срезов и карт, которые кодируются
// to JSON arrays and objects as you'd expect. // в JSON массивы и объекты, как мы и ожидаем.
slcD := []string{"apple", "peach", "pear"} slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD) slcB, _ := json.Marshal(slcD)
fmt.Println(string(slcB)) fmt.Println(string(slcB))
@ -51,73 +52,74 @@ func main() {
mapB, _ := json.Marshal(mapD) mapB, _ := json.Marshal(mapD)
fmt.Println(string(mapB)) fmt.Println(string(mapB))
// The JSON package can automatically encode your // Пакет JSON может автоматически кодировать ваши
// custom data types. It will only include exported // пользовательские типы данных. Он будет включать
// fields in the encoded output and will by default // только экспортируемые поля в закодированный
// use those names as the JSON keys. // вывод и по умолчанию будет использовать эти
// имена в качестве ключей JSON.
res1D := &response1{ res1D := &response1{
Page: 1, Page: 1,
Fruits: []string{"apple", "peach", "pear"}} Fruits: []string{"apple", "peach", "pear"}}
res1B, _ := json.Marshal(res1D) res1B, _ := json.Marshal(res1D)
fmt.Println(string(res1B)) fmt.Println(string(res1B))
// You can use tags on struct field declarations // Вы можете использовать теги в объявлениях
// to customize the encoded JSON key names. Check the // структурных полей для настройки кодированных имен
// definition of `response2` above to see an example // ключей JSON. Проверьте определение `response2`
// of such tags. // выше, чтобы увидеть пример таких тегов.
res2D := &response2{ res2D := &response2{
Page: 1, Page: 1,
Fruits: []string{"apple", "peach", "pear"}} Fruits: []string{"apple", "peach", "pear"}}
res2B, _ := json.Marshal(res2D) res2B, _ := json.Marshal(res2D)
fmt.Println(string(res2B)) fmt.Println(string(res2B))
// Now let's look at decoding JSON data into Go // Теперь давайте рассмотрим декодирование данных
// values. Here's an example for a generic data // JSON в значения Go. Вот пример для общей
// structure. // структуры данных.
byt := []byte(`{"num":6.13,"strs":["a","b"]}`) byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
// We need to provide a variable where the JSON // Нам нужно предоставить переменную, в которую пакет
// package can put the decoded data. This // JSON может поместить декодированные данные.
// `map[string]interface{}` will hold a map of strings // `map[string]interface{} будет содержать карту
// to arbitrary data types. // строк для произвольных типов данных.
var dat map[string]interface{} var dat map[string]interface{}
// Here's the actual decoding, and a check for // Вот фактическое декодирование и проверка на наличие
// associated errors. // ошибок.
if err := json.Unmarshal(byt, &dat); err != nil { if err := json.Unmarshal(byt, &dat); err != nil {
panic(err) panic(err)
} }
fmt.Println(dat) fmt.Println(dat)
// In order to use the values in the decoded map, // Чтобы использовать значения в декодированной карте,
// we'll need to convert them to their appropriate type. // нам нужно преобразовать их в соответствующий тип.
// For example here we convert the value in `num` to // Например, здесь мы конвертируем значение из `num`
// the expected `float64` type. // в ожидаемый тип `float64`.
num := dat["num"].(float64) num := dat["num"].(float64)
fmt.Println(num) fmt.Println(num)
// Accessing nested data requires a series of // Доступ к вложенным данным требует ряда преобразований.
// conversions.
strs := dat["strs"].([]interface{}) strs := dat["strs"].([]interface{})
str1 := strs[0].(string) str1 := strs[0].(string)
fmt.Println(str1) fmt.Println(str1)
// We can also decode JSON into custom data types. // Мы также можем декодировать JSON в пользовательские
// This has the advantages of adding additional // типы данных. Это дает преимущество добавления
// type-safety to our programs and eliminating the // дополнительной безопасности типов в наши программы
// need for type assertions when accessing the decoded // и устранения необходимости в определении типрв
// data. // при доступе к декодированным данным.
str := `{"page": 1, "fruits": ["apple", "peach"]}` str := `{"page": 1, "fruits": ["apple", "peach"]}`
res := response2{} res := response2{}
json.Unmarshal([]byte(str), &res) json.Unmarshal([]byte(str), &res)
fmt.Println(res) fmt.Println(res)
fmt.Println(res.Fruits[0]) fmt.Println(res.Fruits[0])
// In the examples above we always used bytes and // В приведенных выше примерах мы всегда использовали
// strings as intermediates between the data and // байты и строки в качестве промежуточных звеньев между
// JSON representation on standard out. We can also // данными и представлением JSON на стандартном выходе.
// stream JSON encodings directly to `os.Writer`s like // Мы также можем транслировать JSON-кодировки напрямую
// `os.Stdout` or even HTTP response bodies. // в `os.Writer`, такие как `os.Stdout` или даже HTTP-тела
// ответа.
enc := json.NewEncoder(os.Stdout) enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7} d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d) enc.Encode(d)

View File

@ -15,7 +15,6 @@ apple
{"apple":5,"lettuce":7} {"apple":5,"lettuce":7}
# We've covered the basic of JSON in Go here, but check # Мы рассмотрели основы JSON в Go, но ознакомьтесь с
# out the [JSON and Go](http://blog.golang.org/2011/01/json-and-go.html) # публикацией в блоге [JSON and Go](http://blog.golang.org/2011/01/json-and-go.html)
# blog post and [JSON package docs](http://golang.org/pkg/encoding/json/) # и документацией по [пакету JSON](http://golang.org/pkg/encoding/json/).
# for more.