<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>"nodes": [
{"id":"1.1.1.1"}, {"id":2.2.2.2"}
],
"links": [
{ "source":"1.1.1.1", "destination":"2.2.2.2"},
]
</code></pre>
<p>How can I accomplish this in golang? I've been trying to make structs to represent the data but I'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:"id"`
}
type Link struct {
Source string `json:"source"`
Destination string `json:"destination"`
}
type Device struct {
Links []Link `json:"links"`
}
</code></pre>
<p>Next populate it and when done convert it to JSON as follows :</p>
<pre><code>data := &Device{}
data.Source = append(data.Source, ......)
data.Links = append(data.Links, ......)
jsonBytes, err := json.MarshalIndent(data, "", " ") // nice formatting
fmt.Printf("%s\r\n", 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>{
"nodes":[
{
"id":"1.1.1.1"
},
{
"id":"2.2.2.2"
}
],
"links":[
{
"source":"1.1.1.1",
"destination":"2.2.2.2"
}
]
}
type AutoGenerated struct {
Nodes []struct {
ID string `json:"id"`
} `json:"nodes"`
Links []struct {
Source string `json:"source"`
Destination string `json:"destination"`
} `json:"links"`
}
</code></pre></pre>achNichtSoWichtig: <pre><p>What is your struct code?</p>
<p>Also I am pretty sure, you can'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't access them to extract their values.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传