"Go JSON omitempty"의 두 판 사이의 차이

(새 문서: ==개요== ;Go JSON omitempty <syntaxhighlight lang='go' run> package main import ( "encoding/json" "fmt" ) type Fruit struct { Name string `json:"name,omitempty"` Price int...)
 
18번째 줄: 18번째 줄:
a := Fruit{Name: "apple", Price: 42}
a := Fruit{Name: "apple", Price: 42}
b := Fruit{Name: "banana"}
b := Fruit{Name: "banana"}
c := Fruit{Price: 123}
c := Fruit{Name: "melon", Price: 0}
m := Fruit{Name: "melon", Price: 0}
d := Fruit{Price: 123}


aBytes, _ := json.Marshal(a)
aBytes, _ := json.Marshal(a)
bBytes, _ := json.Marshal(b)
bBytes, _ := json.Marshal(b)
cBytes, _ := json.Marshal(c)
cBytes, _ := json.Marshal(c)
mBytes, _ := json.Marshal(m)
dBytes, _ := json.Marshal(d)


fmt.Println(string(aBytes)) // {"name":"apple","price":42}
fmt.Println(string(aBytes)) // {"name":"apple","price":42}
fmt.Println(string(bBytes)) // {"name":"banana"}
fmt.Println(string(bBytes)) // {"name":"banana"}
fmt.Println(string(cBytes)) // {"price":123}
fmt.Println(string(cBytes)) // {"name":"melon"}
fmt.Println(string(mBytes)) // {"name":"melon"}
fmt.Println(string(dBytes)) // {"price":123}
}
}
</syntaxhighlight>
</syntaxhighlight>

2023년 5월 27일 (토) 17:49 판

1 개요

Go JSON omitempty
package main

import (
	"encoding/json"
	"fmt"
)

type Fruit struct {
	Name  string `json:"name,omitempty"`
	Price int    `json:"price,omitempty"`
}

func main() {
	a := Fruit{Name: "apple", Price: 42}
	b := Fruit{Name: "banana"}
	c := Fruit{Name: "melon", Price: 0}
	d := Fruit{Price: 123}

	aBytes, _ := json.Marshal(a)
	bBytes, _ := json.Marshal(b)
	cBytes, _ := json.Marshal(c)
	dBytes, _ := json.Marshal(d)

	fmt.Println(string(aBytes)) // {"name":"apple","price":42}
	fmt.Println(string(bBytes)) // {"name":"banana"}
	fmt.Println(string(cBytes)) // {"name":"melon"}
	fmt.Println(string(dBytes)) // {"price":123}
}

2 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}