잠시만 기다려 주세요

     '검찰공화국, 부패공화국... 윤석열은 내려와라... 그리고 수사 받아라... 당신은 대통령을 할 자격이 없다.'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (19)  |  여러가지 팁 (1095)  |  추천 및 재미 (163)  |  자료실 (28)  |  
시사, 이슈, 칼럼, 평론, 비평 (796)  |  끄적거림 (142)  |  문예 창작 (719)  |  바람 따라 (75)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    golang

golang - golang struct 구조체에 json 사용하기
이 름 : 바다아이   |   조회수 : 10350         짧은 주소 : https://www.bada-ie.com/su/?701591779510
구조체에 json 을 사용할 수 있습니다.
구조체 정의하면서 옆에

`json:"page"`
`json:"fruits"`

이렇게 붙는 것이 요게 핵심입니다.
아래는 예제입니다.


// Go offers built-in support for JSON encoding and
// decoding, including to and from built-in and custom
// data types.

package main

import "encoding/json"
import "fmt"
import "os"

// We'll use these two structs to demonstrate encoding and
// decoding of custom types below.
type response1 struct {
    Page   int
    Fruits []string
}
type response2 struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {

    // First we'll look at encoding basic data types to
    // JSON strings. Here are some examples for atomic
    // values.
    bolB, _ := json.Marshal(true)
    fmt.Println(string(bolB))

    intB, _ := json.Marshal(1)
    fmt.Println(string(intB))

    fltB, _ := json.Marshal(2.34)
    fmt.Println(string(fltB))

    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.
    slcD := []string{"apple", "peach", "pear"}
    slcB, _ := json.Marshal(slcD)
    fmt.Println(string(slcB))

    mapD := map[string]int{"apple": 5, "lettuce": 7}
    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.
    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.
    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.
    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.
    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 cast them to their appropriate type.
    // For example here we cast the value in `num` to
    // the expected `float64` type.
    num := dat["num"].(float64)
    fmt.Println(num)

    // Accessing nested data requires a series of
    // casts.
    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.
    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.
    enc := json.NewEncoder(os.Stdout)
    d := map[string]int{"apple": 5, "lettuce": 7}
    enc.Encode(d)
}


결과 :


true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"Page":1,"Fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
map[num:6.13 strs:[a b]]
6.13
a
{1 [apple peach]}
apple
{"apple":5,"lettuce":7}


출처 : https://gobyexample.com/json
| |





      1 page / 6 page
번 호 카테고리 제 목 이름 조회수
180 golang golang ... 바다아이 126
179 golang golang , ... 바다아이 2704
178 golang golang , map . 바다아이 2094
177 golang Golang (, , data ) , ... 바다아이 2411
176 golang golang sort ... 바다아이 2792
175 golang golang html.EscapeString html.UnescapeString input value ... 바다아이 2717
174 golang golang go.mod go.sum . GOPATH SRC not module, 1.16 . 바다아이 6241
173 golang go 1.16 ... is not in GOROOT.. GOPATH .... . 바다아이 7393
172 golang , String Formatting 바다아이 8703
171 golang rand.Intn , random, , . 바다아이 8224
170 golang golang ... 바다아이 11981
169 golang golang gopath, goroot .. golang 바다아이 8950
168 golang golang ... Force download file example 바다아이 10982
167 golang golang , , cpu, memory, disk 바다아이 12043
166 golang golang , ... GOOS, GOARCH 바다아이 9701
165 golang golang checkbox ... 바다아이 9568
164 golang golang , , http .... 바다아이 9387
163 golang golang nil , nil , nil ... 바다아이 9463
162 golang 2 golang, go , .... golang .... 바다아이 12714
161 golang golang postgresql, mysql, mariadb ... ` Grave () .. .. 바다아이 10024
160 golang golang postgresql mysql, mariadb scan , null .. 바다아이 10088
159 golang golang , iconv 바다아이 12910
158 golang golang quote escape, unquote 바다아이 10324
157 golang golang , http errorLog , , ... 바다아이 10713
156 golang golang interface , 바다아이 9786
155 golang golang struct .... 바다아이 10510
154 golang golang map map , 바다아이 9991
153 golang golang map .... .... 바다아이 9319
152 golang golang slice copy 바다아이 9509
151 golang golang goto 바다아이 10700
| |









Copyright ⓒ 2001.12. bada-ie.com. All rights reserved.
이 사이트는 리눅스에서 firefox 기준으로 작성되었습니다. 기타 브라우저에서는 다르게 보일 수 있습니다.
[ Ubuntu + GoLang + PostgreSQL + Mariadb ]
서버위치 : 오라클 클라우드 춘천  실행시간 : 0.19426
to webmaster... gogo sea. gogo sea.