[go: up one dir, main page]

Skip to content

Using native JSON parsing to realize a slim JSON decoder

shaban edited this page Jan 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 main

import "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.Object
	Value string `js:"value"`
	Href  string `js:"href"`
}

type Popup struct {
	raw       *js.Object
	MenuItems []*MenuItem `js:"menuitem"`
}

type Menu struct {
	raw   *js.Object
	ID    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)
}