Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Using native JSON parsing to realize a slim JSON decoder

shaban edited this pageJan 4, 2018 ·5 revisions

Using native JSON parsing to realize a slim JSON decoder

Sometimes it is undesirable to use the stdlib JSON library especially if your use case necessitates a small filesize.

This small example is meant to highlight some of the advanced features of gopherjs.

Use Cases

Data Store

By writing a small wrapper around the parsed JSON data it is possible to write a convenient data store built around JSON received from a REST server.

Using Structs mapping your application data front and server side.

By using json:"property" struct tags you can conveniently use the stdlib json library serverside and then reuse your structs clientside with the `js:"property" struct tag.Of course it is also possible to use sql struct tags if that is where your data server side comes from.

package mainimport "github.com/gopherjs/gopherjs/js"const json = `{"menu": {  "id": "file",  "value": "File",  "popup": {    "menuitem": [      {"value": "New", "href": "/new"},      {"value": "Open", "href": "/open"},      {"value": "Close", "href": "/close"}    ]  }}}`type MenuItem struct {raw   *js.ObjectValue string `js:"value"`Href  string `js:"href"`}type Popup struct {raw       *js.ObjectMenuItems []*MenuItem `js:"menuitem"`}type Menu struct {raw   *js.ObjectID    string `js:"id"`Value string `js:"value"`Popup *Popup `js:"popup"`}func ParseJSON(responseText string) *js.Object {return js.Global.Get("JSON").Call("parse", responseText)}func main() {obj := ParseJSON(json)if obj == nil {println("Oops soemthing went wrong")return}menuJS := obj.Get("menu")if menuJS == nil {println("Oops no menu")return}m := &Menu{raw: menuJS}println(m.Popup.MenuItems[1].Value)}

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp