2017-12-07 3 views
1

가 여기 내 JSON 파일의 빈 구조체를 반환 패키지가 main로 가져비 정렬 화 JSON은

File content: 
{ 
    "database": { 
     "dialect": "mysql" 
     "host": "localhost", 
     "user": "root", 
     "pass": "", 
     "name": "sws" 
    } 
} 
Conf: {{ }} 
Content: 

Type: config.ConfigType% 

: 여기

package config 

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

type ConfigType struct { 
    Database DatabaseType `json:"database"` 
} 

type DatabaseType struct { 
    Dialect string `json:"dialect"` 
    Host string `json:"host"` 
    User string `json:"user"` 
    Pass string `json:"pass"` 
    Name string `json:"name"` 
} 

func Config() { 
    file, err := os.Open("./config/config.json") 
    if err != nil { 
     log.Fatal(err) 
    } 
    defer file.Close() 

    fileBytes, _ := ioutil.ReadAll(file) 

    var Conf ConfigType 
    json.Unmarshal(fileBytes, &Conf) 

    fmt.Printf("File content:\n%v", string(fileBytes)) 
    fmt.Printf("Conf: %v\n", Conf) 
    fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf) 
} 

그리고 출력 Config 함수 만 실행됩니다. 비슷한 질문을 많이했는데 답안과 거의 똑같은 코드가있는 것 같지만 작동하도록 코드를 가져올 수는 없습니다.

답변

4

왜 앱이 작동하지 않는지에 대해 알 수없는 경우를 제외하고는 오류가 사용자에게 반환되지 않습니다. 오류를 생략하지 마십시오! ioutil.ReadAll()은 오류를 반환합니다. json.Unmarshal()은 오류를 반환합니다. 그걸 확인해!

panic: invalid character '"' after object key:value pair 

Go Playground에이 시도 :

당신은 에러 체크, json.Unmarshal() 수익을 추가해야합니다.

귀하의 입력 JSON이 유효하지 않습니다. "dialect" 줄에 쉼표가 없습니다.

Conf: {{mysql localhost root sws}} 
Content: 
localhost 
Type: main.ConfigType 
0
don't neglect the errors ,always keep track of errors if function is returning one . It helps you find out if somethings goes wrong. 

> In your case json file is invalid you missed "," after "dialect": "mysql" . 
> valid json file should be (config.json) 

    { 
     "database": { 
      "dialect": "mysql", 
      "host": "localhost", 
      "user": "root", 
      "pass": "", 
      "name": "sws" 
     } 
    } 

> 
> 
> Modified code 

    package main 
    import (
     "encoding/json" 
     "fmt" 
     "io/ioutil" 
     "log" 
     "os" 
    ) 

    type ConfigType struct { 
     Database DatabaseType `json:"database"` 
    } 

    type DatabaseType struct { 
     Dialect string `json:"dialect"` 
     Host string `json:"host"` 
     User string `json:"user"` 
     Pass string `json:"pass"` 
     Name string `json:"name"` 
    } 

    func main() { 
     file, err := os.Open("./config.json") 
     if err != nil { 
      log.Fatal(err) 
     } 
     defer file.Close() 

     fileBytes, err := ioutil.ReadAll(file) 
     if err != nil { 
      fmt.Println("error reading file", err) 
      return 
     } 

     var Conf ConfigType 
     err = json.Unmarshal(fileBytes, &Conf) 

     if err != nil { 
      fmt.Println("unmarshalling error ", err) 
      return 
     } 
     fmt.Printf("File content:\n%v\n", string(fileBytes)) 
     fmt.Printf("Conf: %v\n", Conf) 
     fmt.Printf("Content: \n %v \nType: %T", Conf.Database.Host, Conf) 
} 

> Output 

    File content: 
    { 
     "database": { 
     "dialect": "mysql", 
     "host": "localhost", 
     "user": "root", 
     "pass": "", 
     "name": "sws" 
     } 
    } 
    Conf: {{mysql localhost root sws}} 
    Content: 
    localhost 
    Type: main.ConfigType 
: 누락 된 쉼표합니다 ( Go Playground에 그것을 시도)를 추가