【发布时间】:2017-04-29 09:00:06
【问题描述】:
我在本地机器上存储了一个 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 对象?有可能这样做吗? 任何帮助表示赞赏。提前致谢!
【问题讨论】: