Skip to content

Instantly share code, notes, and snippets.

@t-miya
Created September 4, 2017 13:31
Show Gist options
  • Save t-miya/a89b0143ecd73968ae5a010879a44752 to your computer and use it in GitHub Desktop.
Save t-miya/a89b0143ecd73968ae5a010879a44752 to your computer and use it in GitHub Desktop.
Json データ を interface{} でパース後, 再び文字列に戻す際のパーサー
import (
"log"
"reflect"
"strconv"
)
func convertMapToStr(jsonData interface{}) string {
l := []string{}
for key, val := range jsonData.(map[interface{}]interface{}) {
switch reflect.ValueOf(val).Kind() {
case reflect.String:
l = append(l, "\"" + key.(string) + "\":\"" + val.(string) + "\"")
case reflect.Bool:
l = append(l, "\"" + key.(string) + "\":" + strconv.FormatBool(val.(bool)))
case reflect.Int:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(val.(int)))
case reflect.Int8:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(int8))))
case reflect.Int16:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(int16))))
case reflect.Int32:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(int32))))
case reflect.Int64:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(int64))))
case reflect.Uint8:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(uint8))))
case reflect.Uint16:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(uint16))))
case reflect.Uint32:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(uint32))))
case reflect.Uint64:
l = append(l, "\"" + key.(string) + "\":" + strconv.Itoa(int(val.(uint64))))
case reflect.Float64:
// NaN, Inf に備えてちゃんとパースする
l = append(l, "\"" + key.(string) + "\":" + strconv.FormatFloat(val.(float64), 'G', 3, 64))
case reflect.Map:
v := convertMapToStr(val)
l = append(l, "\"" + key.(string) + "\":" + v)
default:
if val == nil {
l = append(l, "\"" + key.(string) + "\":\"\"")
} else {
log.Println("Other type: %v", val)
}
}
}
joined := strings.Join(l, ",")
joined = "{" + joined + "}"
return joined
}
@t-miya
Copy link
Author

t-miya commented Sep 4, 2017

Kinesis の fluentd データを lambda で処理する際に使用.
ProtocolBuffer を変換してきたのでテキスト形式の Json データはなかった.
ログなので入れ子になっており, 階層の深さも一定ではないため再帰で内部の Map も取得.
(多くても5層くらい)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment