小编Ais*_*rya的帖子

我们如何在golang中将json文件作为json对象读取

我有一个存储在本地计算机上的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)
Run Code Online (Sandbox Code Playgroud)

它给了我以下错误,

time="2016-12-13T22:13:05-08:00" level=error msg="Cannot unmarshal the json json: Unmarshal(nil)"
<nil>
Run Code Online (Sandbox Code Playgroud)

尝试2:我尝试将JSON值存储在结构中,然后使用MarshalIndent

generatePlan, _ := json.MarshalIndent(plan, "", " ") // plan is a pointer to a struct
fmt.Println(string(generatePlan))
Run Code Online (Sandbox Code Playgroud)

它给我输出字符串.但是如果我将输出转换为字符串,那么我将无法将其作为JSON对象循环.

我们如何在golang中将JSON文件作为JSON对象读取?有可能吗?任何帮助表示赞赏.提前致谢!

json go file-read

19
推荐指数
2
解决办法
2万
查看次数

标签 统计

file-read ×1

go ×1

json ×1