13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GoのJSONの扱いを簡単にするEasyJsonを作った

Last updated at Posted at 2014-09-21

はじめに

作っておいて何ですが、コッチの方がいいですね
http://qiita.com/hironobu_s/items/602becd6b7f5995503d6

PHPを使っていてそれからGoを触りだしたらJSONの扱いがなんだか面倒くさい。
静的言語と動的言語の差なんだろうかと諦めてたら、
Swiftは、簡単にする実装とかされてますね・・・

Swiftで面倒なJSONの取り扱いをさらに10倍便利にするclass JSON

Goでやってみました

更にメソッドを追加してerrを返却しない代わりにpanicを起こす AsXXXPanicメソッドを追加しました
より簡単に使えるようになりました

実装例

example.go

package main

import (
    "github.com/m0a/easyjson"
    "net/http"
    "fmt"
)


func main() {

	url := "http://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&sensor=false"

	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}

	if resp.StatusCode != http.StatusOK {
		panic(resp.StatusCode)
	}

	json,err := easyjson.NewEasyJson(resp.Body)
	if err!=nil {
		panic("json convert err")
	}

	//easy access!
	json.K("routes",0,"bounds","southwest").PrettyPrint()

	//support method chain
	json.K("routes").K(0).K("bounds").K("southwest").PrettyPrint()

    // if use loop
	for k,v:=range json.K("routes").K(0).RangeObjects() {
		fmt.Printf("%v:%v\n",k,v)
	}

	//string value
	copyrights,err:=json.K("routes").K(0).K("copyrights").AsString()
	if err!=nil {
		panic("AsString err")
	}


	fmt.Printf("copyrights=%s",copyrights)

	//more easy use
	fmt.Printf("copyrights=%s", json.AsStringPanic("routes", 0, "copyrights"))


}

Goには演算子のオーバーロードがないのでKでアクセスするようにしました
easyjson.NewEasyJsonにio.Readerかstringか
Goのオブジェクト([]interface{}map[string]interface{}の組み合わせであること)を与えてやると動きます

参考

13
14
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
13
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?