Noob Gopher Help for JSON to Map

polaris · · 491 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi guys,</p> <p>New to Golang (and programming in general) - so apologies first if this is not the right place to post such queries.</p> <p>My question is what is the best way to bring in JSON code into a Golang map?</p> <p>I should also add - the JSON file is an external file, and not part of the main source { &#34;data&#34; : { &#34;field1&#34; : &#34;value1&#34;, &#34;field2&#34; : &#34;value2&#34; } }</p> <p>Any assistance, even if its links, will be appreciated.</p> <hr/>**评论:**<br/><br/>dlq84: <pre><p>I always prefer to map it to structs, so that I don&#39;t have to do type assertions and stuff like that. So in your case it would be</p> <pre><code>type MyJson struct { Data struct { Field1 string `json:&#34;field1&#34;` Field2 string `json:&#34;field2&#34;` } `json:&#34;data&#34;` } </code></pre> <p>And then you simply parse it like so:</p> <pre><code>var json MyJson json.Unmarshal(jsonByteSlice, &amp;json) // Don&#39;t forget to check for errors here. </code></pre> <p>Check out the <a href="https://golang.org/pkg/encoding/json/" rel="nofollow">json package</a> for more information</p></pre>SSJ3Vegeta: <pre><p>Your&#39;re an absolute diamond. Have an upvote :-)</p></pre>dlq84: <pre><p>Thanks, glad to help. Remember that missing fields will be empty string or 0 in case of integers, or whatever the type would be per default if you simply declared a variable. So if this is supposed to be used in production where you necessarily might not have control over the input, use any of the json validation libs out there. One example of such a lib is: <a href="https://github.com/michaeljs1990/val" rel="nofollow">https://github.com/michaeljs1990/val</a></p></pre>mwholt: <pre><p>You might like <a href="https://mholt.github.io/json-to-go/" rel="nofollow">https://mholt.github.io/json-to-go/</a> although it takes the data directly to a struct, not a map.</p></pre>Redundancy_: <pre><p>This can be a massively useful.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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