<p>If I have a struct
type Person struct {
Name string `json:"Name"
IsSleeping bool 'json:"IsSleeping"
}</p>
<p>how do I only print the name using json.Marshal()</p>
<hr/>**评论:**<br/><br/>wwader: <pre><p>Try:</p>
<pre><code>IsSleeping bool `json:"-"`
</code></pre></pre>XQZ025: <pre><p>Thank you so much!</p></pre>Akkifokkusu: <pre><p>If you don't need to <code>Unmarshal</code> into <code>IsSleeping</code>, you can use <code>`json:"-"`</code>. If you don't need the field to be exported, you can also just change it to <code>isSleeping</code>.</p>
<p>If you need to be able to <code>Unmarshal</code> it, but don't want it <code>Marshal</code>ed back out, you can use embedding.</p>
<pre><code>type DisplayPerson struct {
Name string `json:"Name"`
}
type Person struct {
DisplayPerson
IsSleeping bool `json:"IsSleeping"`
}
func main() {
var p Person
json.Unmarshal([]byte(`{"Name":"John Doe", "IsSleeping":true}`), &p)
disp, _ := json.Marshal(p.DisplayPerson)
fmt.Println(string(disp)) // {"Name":"John Doe"}
}
</code></pre>
<p><a href="https://play.golang.org/p/eSGOYC1uk1" rel="nofollow">https://play.golang.org/p/eSGOYC1uk1</a></p></pre>XQZ025: <pre><p>That's good to know, thank you!</p></pre>dlsniper: <pre><p>If you never want to marshal a value in json, do the json:"-" tag to the field. Else you have to implement your own marshaller for the type and add logic there. </p></pre>XQZ025: <pre><p>Ok thank you!</p></pre>mishudark: <pre><p>I have a fork from encode/json which support the labels, <em>omitunmarshal</em> and <em>omitmarshal</em>, example:</p>
<pre><code>type User struct{
Name string `json:"name"`,
Password string `json:"password,omitmarshal"`
}
</code></pre>
<p>then you can unmarshal the password field, but when you encode this struct, it omits the <em>password</em> field</p>
<p>Any interested in this patch, should you think I should make a pull request to go?</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传