Print only some attributes of a struct in JSON

xuanbao · · 408 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>If I have a struct type Person struct { Name string `json:&#34;Name&#34; IsSleeping bool &#39;json:&#34;IsSleeping&#34; }</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:&#34;-&#34;` </code></pre></pre>XQZ025: <pre><p>Thank you so much!</p></pre>Akkifokkusu: <pre><p>If you don&#39;t need to <code>Unmarshal</code> into <code>IsSleeping</code>, you can use <code>`json:&#34;-&#34;`</code>. If you don&#39;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&#39;t want it <code>Marshal</code>ed back out, you can use embedding.</p> <pre><code>type DisplayPerson struct { Name string `json:&#34;Name&#34;` } type Person struct { DisplayPerson IsSleeping bool `json:&#34;IsSleeping&#34;` } func main() { var p Person json.Unmarshal([]byte(`{&#34;Name&#34;:&#34;John Doe&#34;, &#34;IsSleeping&#34;:true}`), &amp;p) disp, _ := json.Marshal(p.DisplayPerson) fmt.Println(string(disp)) // {&#34;Name&#34;:&#34;John Doe&#34;} } </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&#39;s good to know, thank you!</p></pre>dlsniper: <pre><p>If you never want to marshal a value in json, do the json:&#34;-&#34; 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:&#34;name&#34;`, Password string `json:&#34;password,omitmarshal&#34;` } </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

408 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传