我有一个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对象?是否可能做到这一点?非常感谢您的帮助!
err := json.Unmarshal(fileBytes, spec)
中的spec
是什么意思?抱歉,我是 GoLang 的新手,正在逐渐熟悉这门语言。 - Jason