LoginSignup
5
2

More than 3 years have passed since last update.

Go でローカルにある JSON を読み込む

Posted at

やりたいこと

ローカルにある JSON を Go の構造体として読み込む

ローカルにある JSON ファイル (sample.json)


{
  "posts": [
    {
      "id": 1,
      "title": "Post 1"
    },
    {
      "id": 2,
      "title": "Post 2"
    },
    {
      "id": 3,
      "title": "Post 3"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    },
    {
      "id": 2,
      "body": "some comment",
      "postId": 1
    }
  ]
}

JSON を struct でどう読み込むか決める

type Post struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
}

type Comment struct {
    ID     int    `json:"id"`
    Body   string `json:"body"`
    PostID int    `json:"postId"`
}

type Blog struct {
    Posts    []Post    `json:"posts"`
    Comments []Comment `json:"comments"`
}

Unmarshal で構造体に変換

json.Unmarshal で JSON を構造体に変換

func main() {

    jsonFromFile, err := ioutil.ReadFile("./sample.json")
    if err != nil {
        log.Fatal(err)
    }

    var jsonData Blog
    err = json.Unmarshal(jsonFromFile, &jsonData)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(jsonData.Posts[0].Title)
}

最後に読み込めているか確認
Post 1 と出力されれば成功。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2