json
This commit is contained in:
parent
e69f56644e
commit
1660a57d5f
@ -1,6 +1,6 @@
|
||||
// Go offers built-in support for JSON encoding and
|
||||
// decoding, including to and from built-in and custom
|
||||
// data types.
|
||||
// Go предлагает встроенную поддержку кодирования и
|
||||
// декодирования JSON, в том числе встроенных и
|
||||
// пользовательских типов данных.
|
||||
|
||||
package main
|
||||
|
||||
@ -10,15 +10,16 @@ import (
|
||||
"os"
|
||||
)
|
||||
|
||||
// We'll use these two structs to demonstrate encoding and
|
||||
// decoding of custom types below.
|
||||
// Мы будем использовать эти две структуры, для демонстрации
|
||||
// кодирования и декодирования.
|
||||
type response1 struct {
|
||||
Page int
|
||||
Fruits []string
|
||||
}
|
||||
|
||||
// Only exported fields will be encoded/decoded in JSON.
|
||||
// Fields must start with capital letters to be exported.
|
||||
// Только экспортируемые поля могут быть кодированы и
|
||||
// декодированы в JSON. Поля должны начинаться с
|
||||
// заглавной буквы.
|
||||
type response2 struct {
|
||||
Page int `json:"page"`
|
||||
Fruits []string `json:"fruits"`
|
||||
@ -26,9 +27,9 @@ type response2 struct {
|
||||
|
||||
func main() {
|
||||
|
||||
// First we'll look at encoding basic data types to
|
||||
// JSON strings. Here are some examples for atomic
|
||||
// values.
|
||||
// Для начала мы рассмотрим кодирование данных в
|
||||
// JSON строку. Вот несколько примеров для простых
|
||||
// типов данных.
|
||||
bolB, _ := json.Marshal(true)
|
||||
fmt.Println(string(bolB))
|
||||
|
||||
@ -41,8 +42,8 @@ func main() {
|
||||
strB, _ := json.Marshal("gopher")
|
||||
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"}
|
||||
slcB, _ := json.Marshal(slcD)
|
||||
fmt.Println(string(slcB))
|
||||
@ -51,73 +52,74 @@ func main() {
|
||||
mapB, _ := json.Marshal(mapD)
|
||||
fmt.Println(string(mapB))
|
||||
|
||||
// The JSON package can automatically encode your
|
||||
// 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 может автоматически кодировать ваши
|
||||
// пользовательские типы данных. Он будет включать
|
||||
// только экспортируемые поля в закодированный
|
||||
// вывод и по умолчанию будет использовать эти
|
||||
// имена в качестве ключей JSON.
|
||||
res1D := &response1{
|
||||
Page: 1,
|
||||
Fruits: []string{"apple", "peach", "pear"}}
|
||||
res1B, _ := json.Marshal(res1D)
|
||||
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
|
||||
// of such tags.
|
||||
// Вы можете использовать теги в объявлениях
|
||||
// структурных полей для настройки кодированных имен
|
||||
// ключей JSON. Проверьте определение `response2`
|
||||
// выше, чтобы увидеть пример таких тегов.
|
||||
res2D := &response2{
|
||||
Page: 1,
|
||||
Fruits: []string{"apple", "peach", "pear"}}
|
||||
res2B, _ := json.Marshal(res2D)
|
||||
fmt.Println(string(res2B))
|
||||
|
||||
// Now let's look at decoding JSON data into Go
|
||||
// values. Here's an example for a generic data
|
||||
// structure.
|
||||
// Теперь давайте рассмотрим декодирование данных
|
||||
// JSON в значения Go. Вот пример для общей
|
||||
// структуры данных.
|
||||
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
|
||||
|
||||
// We need to provide a variable where the JSON
|
||||
// package can put the decoded data. This
|
||||
// `map[string]interface{}` will hold a map of strings
|
||||
// to arbitrary data types.
|
||||
// Нам нужно предоставить переменную, в которую пакет
|
||||
// JSON может поместить декодированные данные.
|
||||
// `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 {
|
||||
panic(err)
|
||||
}
|
||||
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
|
||||
// the expected `float64` type.
|
||||
// Чтобы использовать значения в декодированной карте,
|
||||
// нам нужно преобразовать их в соответствующий тип.
|
||||
// Например, здесь мы конвертируем значение из `num`
|
||||
// в ожидаемый тип `float64`.
|
||||
num := dat["num"].(float64)
|
||||
fmt.Println(num)
|
||||
|
||||
// Accessing nested data requires a series of
|
||||
// conversions.
|
||||
// Доступ к вложенным данным требует ряда преобразований.
|
||||
strs := dat["strs"].([]interface{})
|
||||
str1 := strs[0].(string)
|
||||
fmt.Println(str1)
|
||||
|
||||
// We can also decode JSON into custom data types.
|
||||
// This has the advantages of adding additional
|
||||
// type-safety to our programs and eliminating the
|
||||
// need for type assertions when accessing the decoded
|
||||
// data.
|
||||
// Мы также можем декодировать JSON в пользовательские
|
||||
// типы данных. Это дает преимущество добавления
|
||||
// дополнительной безопасности типов в наши программы
|
||||
// и устранения необходимости в определении типрв
|
||||
// при доступе к декодированным данным.
|
||||
str := `{"page": 1, "fruits": ["apple", "peach"]}`
|
||||
res := response2{}
|
||||
json.Unmarshal([]byte(str), &res)
|
||||
fmt.Println(res)
|
||||
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
|
||||
// stream JSON encodings directly to `os.Writer`s like
|
||||
// `os.Stdout` or even HTTP response bodies.
|
||||
// В приведенных выше примерах мы всегда использовали
|
||||
// байты и строки в качестве промежуточных звеньев между
|
||||
// данными и представлением JSON на стандартном выходе.
|
||||
// Мы также можем транслировать JSON-кодировки напрямую
|
||||
// в `os.Writer`, такие как `os.Stdout` или даже HTTP-тела
|
||||
// ответа.
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
d := map[string]int{"apple": 5, "lettuce": 7}
|
||||
enc.Encode(d)
|
||||
|
@ -15,7 +15,6 @@ apple
|
||||
{"apple":5,"lettuce":7}
|
||||
|
||||
|
||||
# We've covered the basic of JSON in Go here, but check
|
||||
# out the [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/)
|
||||
# for more.
|
||||
# Мы рассмотрели основы JSON в Go, но ознакомьтесь с
|
||||
# публикацией в блоге [JSON and Go](http://blog.golang.org/2011/01/json-and-go.html)
|
||||
# и документацией по [пакету JSON](http://golang.org/pkg/encoding/json/).
|
||||
|
Loading…
x
Reference in New Issue
Block a user