我有一个JSON文件存储在本地机器上。我需要在一个变量中读取它并循环它来获取JSON对象值。如果我在使用ioutil.Readfile方法阅读文件后使用Marshal命令,它会给出一些数字作为输出。这些是我少数失败的尝试,
尝试1:
plan, _ := ioutil.ReadFile(filename) // filename is the JSON file to read
var data interface{}
err := json.Unmarshal(plan, data)
if err != nil {
log.Error("Cannot unmarshal the json ", err)
}
fmt.Println(data)
字符串
它给了我以下错误,
time="2016-12-13T22:13:05-08:00" level=error msg="Cannot unmarshal the json json: Unmarshal(nil)"
<nil>
型
尝试2:我尝试将JSON值存储在结构中,然后使用MarshalIndent
generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct
fmt.Println(string(generatePlan))
型
它给予字符串的输出,但是如果我把输出转换成字符串,那么我就不能把它作为JSON对象循环。
我们如何在golang中读取JSON文件作为JSON对象?有可能吗?任何帮助都很感激。提前感谢!
3条答案
按热度按时间wecizke31#
json.Unmarshal
填充的值必须是指针。GoDoc:
Unmarshal解析JSON编码的数据,并将结果存储在v指向的值中。
因此,您需要执行以下操作:
字符串
您的错误(Unmarshal(nil))表明在阅读文件时出现了一些问题,请检查
ioutil.ReadFile
返回的错误另外请注意,当在unmarshal中使用空接口时,您需要使用type assertion来获取底层值作为go原语类型。
要将JSON解组为接口值,Unmarshal会在接口值中存储以下内容之一:
型
使用
Unmarshal
使用具体的结构来填充json总是一个更好的方法。ou6hu8tu2#
如果你在2022年看到这个,
ioutil
包已经被弃用了。你仍然可以使用它,但你会得到烦人的错误。相反,你可以使用os包。
字符串
注意,我特意忽略了
os.ReadFile
的错误,因为它也会导致json.Unmarshal
的错误。fjaof16o3#
随着泛型的引入,这已经成为一个非常有用的片段。
字符串