-1

I am currently learning Golang and I jumped into the issue with following code

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)
}

I receive this error when I issue 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)

So I wonder what could be the problem, I even tried importing json encoding/json and it still seems that this import is not taken into the account. So any ideas? I have a version 1.12.4 instaled.

Petr Mensik
  • 26,874
  • 17
  • 90
  • 115

1 Answers1

7

json, err := ioutil.ReadFile("gopher.json") defines json as variable which overrides json package in that scope.

Try this

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)
}
Gaurav Dhiman
  • 1,163
  • 6
  • 8