我有一个JSON文件存储在本地机器上。我需要在一个变量中读取它并循环通过它来获取JSON对象值。如果在使用ioutil.Readfile方法读取文件后使用Marshal命令,则会将一些数字作为输出。这些都是我的一些失败的尝试,我们如何读取json文件作为golang中的json对象
尝试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对象进行循环。
我们如何读取一个JSON文件作为golang中的JSON对象?有可能这样做吗? 任何帮助表示赞赏。提前致谢!