IT

Go 구조체를 JSON으로 변환

lottoking 2020. 6. 12. 08:34
반응형

Go 구조체를 JSON으로 변환


json패키지를 사용하여 Go 구조체를 JSON으로 변환하려고 하지만 얻는 것은 {}입니다. 나는 그것이 완전히 명백한 것이 확실하지만 그것을 보지 못한다.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func main() {
    user := &User{name:"Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Printf("Error: %s", err)
        return;
    }
    fmt.Println(string(b))
}

그런 다음 실행하려고하면이를 얻습니다.

$ 6g test.go && 6l -o test test.6 && ./test 
{}

당신은 할 필요가 수출User.name 있도록 필드에 json패키지를 볼 수 있습니다. name필드 이름을로 바꿉니다 Name.

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    Name string
}

func main() {
    user := &User{Name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

산출:

{"Name":"Frank"}

관련 문제 :

구조체를 JSON으로 변환하고 Golang의 응답으로 보낸 다음 나중에 Ajax를 통해 JavaScript에서 동일하게 catch하는 데 문제가있었습니다.

많은 시간을 낭비 했으므로 여기에 솔루션을 게시하십시오.

이동 중 :

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

자바 스크립트에서 :

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

이것이 누군가를 돕기를 바랍니다.
행운을 빌어 요.


구조 값은 JSON 객체로 인코딩됩니다. 다음과 같은 경우를 제외하고 내 보낸 각 구조체 필드는 객체의 멤버가됩니다.

  • 필드의 태그가 "-"이거나
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.


You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

참고URL : https://stackoverflow.com/questions/8270816/converting-go-struct-to-json

반응형