LoginSignup
36
28

More than 5 years have passed since last update.

Goで値が文字列のJSONを構造体にパースする

Last updated at Posted at 2016-05-09

やよい軒のメニューをJSONで渡された場面を想定してください

yayoiken.go
package main

import (
    "encoding/json"
    "fmt"
)

type Food struct {
    Name    string  `json:"name"`
    Price   float64 `json:"price"`
    Okawari bool    `json:"okawari"`
}

func main() {
    yayoiken_str := `[
    {
      "name": "なす味噌と焼魚の定食",
      "price" : "880",
      "okawari" : "true"
    },
    {
      "name": "しょうが焼き定食",
      "price" : "630",
      "okawari" : "true"
    },
    {
      "name": "桜島どりの親子丼",
      "price" : "650",
      "okawari" : "false"
    }
]`
    var food []Food
    err := json.Unmarshal([]byte(yayoiken_str), &food)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(food)
}
json: cannot unmarshal string into Go value of type float64

実はこれ、PriceとOkawariは型が違うのでパース出来ません。
文字列でboolやintが渡ってきた時に良しなにしてくれません。

公式よく読むと
https://golang.org/pkg/encoding/json/#Marshal
json:",string"で文字列いい感じにしてくれるっぽい

こんな感じに修正する

food.go
type Food struct {
    Name    string  `json:"name"`
    Price   float64 `json:"price,string"`
    Okawari bool    `json:"okawari,string"`
}

結果

[{なす味噌と焼魚の定食 880 true} {しょうが焼き定食 630 true} {桜島どりの親子丼 650 false}]

~fin~

36
28
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
36
28