Help making JSON data

blov · · 431 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello, I am trying to take data in, and output it in a specific JSON format. The final format of the data should be a text file presented as shown below:</p> <pre><code>&#34;nodes&#34;: [ {&#34;id&#34;:&#34;1.1.1.1&#34;}, {&#34;id&#34;:2.2.2.2&#34;} ], &#34;links&#34;: [ { &#34;source&#34;:&#34;1.1.1.1&#34;, &#34;destination&#34;:&#34;2.2.2.2&#34;}, ] </code></pre> <p>How can I accomplish this in golang? I&#39;ve been trying to make structs to represent the data but I&#39;m not having much luck unfortunately. </p> <hr/>**评论:**<br/><br/>janderssen: <pre><p>Create a struct as follows </p> <pre><code>type Node struct { ID string `json:&#34;id&#34;` } type Link struct { Source string `json:&#34;source&#34;` Destination string `json:&#34;destination&#34;` } type Device struct { Links []Link `json:&#34;links&#34;` } </code></pre> <p>Next populate it and when done convert it to JSON as follows :</p> <pre><code>data := &amp;Device{} data.Source = append(data.Source, ......) data.Links = append(data.Links, ......) jsonBytes, err := json.MarshalIndent(data, &#34;&#34;, &#34; &#34;) // nice formatting fmt.Printf(&#34;%s\r\n&#34;, string(jsonBytes)) </code></pre> <p>Cheers</p></pre>monkey-go-code: <pre><p>This is the right answer. </p></pre>shovelpost: <pre><p>You can use <a href="https://mholt.github.io/json-to-go/">mholt.github.io/json-to-go</a> to generate a quick and dirty struct for Go from JSON input:</p> <pre><code>{ &#34;nodes&#34;:[ { &#34;id&#34;:&#34;1.1.1.1&#34; }, { &#34;id&#34;:&#34;2.2.2.2&#34; } ], &#34;links&#34;:[ { &#34;source&#34;:&#34;1.1.1.1&#34;, &#34;destination&#34;:&#34;2.2.2.2&#34; } ] } type AutoGenerated struct { Nodes []struct { ID string `json:&#34;id&#34;` } `json:&#34;nodes&#34;` Links []struct { Source string `json:&#34;source&#34;` Destination string `json:&#34;destination&#34;` } `json:&#34;links&#34;` } </code></pre></pre>achNichtSoWichtig: <pre><p>What is your struct code?</p> <p>Also I am pretty sure, you can&#39;t just have to key-value-pairs by themself, you probably need at least surrounding curly braces.</p></pre>kpurdon: <pre><p>Here is an example reading in the JSON output you pasted: <a href="https://play.golang.org/p/HPTW9PuFl0" rel="nofollow">https://play.golang.org/p/HPTW9PuFl0</a></p> <p>Depends on what your input data is though.</p></pre>templarrei: <pre><p>Try this one:</p> <p><a href="https://play.golang.org/p/qKD7LDSveG" rel="nofollow">https://play.golang.org/p/qKD7LDSveG</a></p> <p>Just be careful to not name your property names with lowercase. That makes them private and the json package can&#39;t access them to extract their values.</p></pre>

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

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