<p>I'm trying to add a golang example in <a href="https://github.com/samayo/country-data" rel="nofollow">https://github.com/samayo/country-data</a> or <a href="https://github.com/samayo/country-data/issues/20" rel="nofollow">this issues</a> I can't find much info on this. Mainly because I don't know anything about go. </p>
<p>If anyone know, I appreciate the help. </p>
<hr/>**评论:**<br/><br/>sahne: <pre><p>You might want something like this</p>
<pre><code>import (
"io/ioutil"
"encoding/json"
)
type MyData struct {
Foo string `json:"foo"`
Bar float64 `json:"bar,omitempty"`
}
func parseData(filename string) (&MyData, error) {
data := MyData{}
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
if err := json.Unmarshal(content, &data); err != nil {
return nil, err
}
return &data, nil
}
</code></pre></pre>dim13: <pre><p><a href="https://golang.org/pkg/encoding/json/#example_Unmarshal" rel="nofollow">https://golang.org/pkg/encoding/json/#example_Unmarshal</a></p></pre>iCupid: <pre><p>Yeah, I've seen that. Is there any example that is simpler? Like shown in the link? Plus, this example is not even fetching it from a JSON file. That is not what I wanted to show.</p></pre>chrj: <pre><p>Open the file with <a href="https://godoc.org/os#Open" rel="nofollow"><code>os.Open</code></a>. This gives you an <a href="https://godoc.org/io#Reader" rel="nofollow"><code>io.Reader</code></a> compatible value that can be processed using <a href="https://godoc.org/encoding/json#NewDecoder" rel="nofollow"><code>json.NewDecoder</code></a>.</p></pre>dim13: <pre><p>You can use <a href="https://golang.org/pkg/io/ioutil/#ReadFile" rel="nofollow">ioutil.ReadFile</a> or method suggested by <a href="/u/chrj" rel="nofollow">chrj</a>.</p>
<p>Anyway, I don't really see, why such example is mandatory. People who use Go know how to read a file and get json data out of it. ;)</p></pre>pafortin: <pre><p>From the data I see the project he referenced you cannot use a specific struct to unmarshall the data only a map.</p></pre>pafortin: <pre><p>See if this helps - <a href="https://play.golang.org/p/SmsritdOML" rel="nofollow">https://play.golang.org/p/SmsritdOML</a></p></pre>iCupid: <pre><p>I don't get it. Isn't there a way to require or import a json file in go? as in <code>require 'country-data.json'</code> because in the example the json content is hard-coded.</p></pre>pafortin: <pre><p>You need to write code to load the data. search google "golang read flle" There are tons of examples.</p></pre>dim13: <pre><p>No, you cannot simply import json.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传