已导入但未在 JSON 解析器中使用的包

Pet*_*sik -1 linux json go

我目前正在学习 Golang,我使用以下代码跳入了这个问题

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "encoding/json"
)

func main() {
    json, err := ioutil.ReadFile("gopher.json")
    if err != nil {
        fmt.Println("Error opening file")
        os.Exit(1)
    }
    var dat map[string]interface{}
    if err := json.Unmarshal(json, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}
Run Code Online (Sandbox Code Playgroud)

我发出时收到此错误 go run main.go

./main.go:7:5: imported and not used: "encoding/json"
./main.go:18:16: json.Unmarshal undefined (type []byte has no field or method Unmarshal)
Run Code Online (Sandbox Code Playgroud)

所以我想知道可能是什么问题,我什至尝试导入json encoding/json,但似乎仍然没有考虑到这个导入。那么有什么想法吗?我安装了 1.12.4 版本。

Gau*_*man 7

json, err := ioutil.ReadFile("gopher.json")定义json为覆盖json该范围内的包的变量。

尝试这个

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "encoding/json"
)

func main() {
    jsonFile, err := ioutil.ReadFile("gopher.json")
    if err != nil {
        fmt.Println("Error opening file")
        os.Exit(1)
    }
    var dat map[string]interface{}
    if err := json.Unmarshal(jsonFile, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)
}
Run Code Online (Sandbox Code Playgroud)