nosj

package module
v0.0.0-...-c99a6ab Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 1, 2017 License: MIT Imports: 5 Imported by: 0

README

NOSJ - Tiny Simple JSON Reflection in Go

This is to make testing JSON output of whatever-you're-doing a tiny bit easier.

GoDoc

Quick start

For full details of the below examples, see this file.

First: import nosj, ginkgo and gomega:

import (
	"github.com/totherme/nosj"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

Next, get yourself some nosj.JSON:

rawjson := `{...}`

myjson, err = nosj.ParseJSON(rawjson)
Expect(err).NotTo(HaveOccurred())

Test!

It("contains three employees", func() {
	employees, err := myjson.GetByPointer("/employees")
	Expect(err).NotTo(HaveOccurred())
	Expect(employees).To(BeAList())
	Expect(employees.ListValue()).To(HaveLen(3))
})

Describe("the first employee", func() {
	It("is great at cooking", func() {
		skill, err := myjson.GetByPointer("/employees/0/profile/special-skill")
		Expect(err).NotTo(HaveOccurred())
		Expect(skill).To(BeAString())
		Expect(skill.StringValue()).To(Equal("szechuan cookery"))
	})
})

In addition to nosj's JSON-wrangling, these tests make use of the ginkgo BDD DSL, which provides constructs like Describe and It; and the gomega matcher library, which gives us Expect.

Getting nosj.JSON Values

There are two approaches you can take to pulling values out of a nosj.JSON object. Firstly, if you like JSON pointers, you can use them:

morejson, err := myjson.GetByPointer("/path/to/property")

The other approach is to get by one key at a time. For this, you can use GetField or its alias F:

morejson := myjson.GetField("path").GetField("to").GetField("property")
// or equivalently:
morejson := myjson.F("path").F("to").F("property")

Note that all these methods will return another nosj.JSON object to the variable morejson. To do anything interesting, you'll probably want to get a golang value out of the nosj.JSON object, as documented in 'Getting Golang Values' below. Finally, notice that while GetByPointer's return type includes an error (e.g. when the pointer does not exist in myjson), the return type of GetField does not. This allows GetField to be chained (and thus makes up for single-field names being significantly less expressive than JSON pointers), but does mean that GetField will panic in those occasions where GetByPointer would return a helpful error message.

Testing nosj.JSON Values

nosj.JSON values may represent data of a variety of golang types. To discover these types, you can use methods such as:

isJSONBool := myjson.IsBool()
isJSONNum := myjson.IsNum()
isJSONString := myjson.IsString()
isJSONOb := myjson.IsOb()
isJSONList := myjson.IsList()
isJSONNull := myjson.IsNull()

If your nosj.JSON object represents a JSON object (as opposed to, for example, a JSON String), you may also want to check if that object has a field of a particular name:

hasField := myjson.HasKey("particular-name")

Getting Golang Values

If you are sure what JSON type is represented by your nosj.JSON object, you can get a value of the appropriate golang type like so:

myGolangBool := myjson.BoolValue()
myGolangNum := myjson.NumValue()
myGolangString := myjson.StringValue()
myGolangOb := myjson.ObValue()
myGolangList := myjson.ListValue()

Matchers

If you're using ginkgo and gomega, you might prefer to use a matcher rather than test your JSON directly:

import (
	"github.com/totherme/nosj"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/totherme/nosj/gnosj"
)

var _ = Describe("Gnosj matchers", func() {
  It("does the same thing as our test methods", func() {
    // Type matchers
    Expect(myjson.IsBool()).To(BeTrue())
    Expect(myjson).To(BeABool())

    Expect(myjson.IsNum()).To(BeTrue())
    Expect(myjson).To(BeANum())

    Expect(myjson.IsString()).To(BeTrue())
    Expect(myjson).To(BeAString())

    Expect(myjson.IsOb()).To(BeTrue())
    Expect(myjson).To(BeAnObject())

    Expect(myjson.IsList()).To(BeTrue())
    Expect(myjson).To(BeAList())

    Expect(myjson.IsNull()).To(BeTrue())
    Expect(myjson).To(BeANull())

    // Access matchers
    Expect(myjson.HasKey("my-key")).To(BeTrue())
    Expect(myjson).To(HaveJSONKey("my-key"))

    Expect(myjson.HasPointer("/my/pointer")).To(BeTrue())
    Expect(myjson).To(HaveJSONPointer("/my/pointer"))
  })
})

Each pair of expectations in the above block is composed of two equivalent statements.

Documentation

Overview

Package nosj provides lightweight JSON reflection for testing.

Index

Constants

View Source
const (
	JSONString = "string"
	JSONNum    = "number"
	JSONOb     = "object"
	JSONList   = "list"
	JSONNull   = "null"
	JSONBool   = "bool"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type JSON

type JSON struct {
	// contains filtered or unexported fields
}

JSON represents a parsed json structure.

func ParseJSON

func ParseJSON(rawjson string) (JSON, error)

ParseJSON unmarshals yaml from an input string. Use this for generating a JSON struct, whose contents you can examine using the following functions.

func ParseYAML

func ParseYAML(rawjson string) (JSON, error)

ParseYAML unmarshals json from an input string. Use this for generating a YAML struct, whose contents you can examine using the following functions.

func (JSON) BoolValue

func (j JSON) BoolValue() bool

BoolValue returns the golang bool representation of the json bool represented by this JSON struct. If the JSON struct does not represent a json bool, this method panics. If in doubt, check with `IsBool()`

func (JSON) F

func (j JSON) F(key string) JSON

F is a shorthand for `GetField`

func (JSON) GetByPointer

func (j JSON) GetByPointer(p string) (nosj JSON, err error)

GetByPointer returns a JSON struct containing the contents of the original json at the given pointer address `p`. For more information on json pointers, see https://tools.ietf.org/html/rfc6901

func (JSON) GetField

func (j JSON) GetField(key string) JSON

GetField returns a JSON struct containing the contents of the original json at the given `key`. If this method name feels too long, use `F(key)`.

Note: this function panics if the given `key` does not exist. If in doubt, check with `HasKey()`.

func (JSON) HasKey

func (j JSON) HasKey(key string) bool

HasKey returns true iff the json object represented by this JSON struct contains `key`

Note: this will panic if the json represented by this JSON struct is not a json object. If in doubt, check with `IsOb()`

func (JSON) HasPointer

func (j JSON) HasPointer(p string) (bool, error)

HasPointer returns true iff the json object represented by this JSON struct contains the pointer `p`

For more information on json pointers, see https://tools.ietf.org/html/rfc6901

func (JSON) IsBool

func (j JSON) IsBool() bool

IsBool returns true iff the json represented by this JSON struct is a boolean.

func (JSON) IsList

func (j JSON) IsList() bool

IsList returns true iff the json represented by this JSON struct is a json list.

func (JSON) IsNull

func (j JSON) IsNull() bool

IsNull returns true iff the json represented by this JSON struct is json null.

func (JSON) IsNum

func (j JSON) IsNum() bool

IsNum returns true iff the json represented by this JSON struct is a number.

func (JSON) IsOb

func (j JSON) IsOb() bool

IsOb returns true iff the json represented by this JSON struct is a json object.

func (JSON) IsOfType

func (j JSON) IsOfType(typ string) bool

IsOfType returns true iff the JSON struct represents a json of type `typ`. Valid values of `typ` are listed as constants above.

func (JSON) IsString

func (j JSON) IsString() bool

IsString returns true iff the json represented by this JSON struct is a string.

func (JSON) ListValue

func (j JSON) ListValue() (list []JSON)

ListValue returns a golang slice of JSON structs representing the json list represented by this JSON struct. If the JSON struct does not represent a json list, this method panics. If in doubt, check with `IsList()`

func (JSON) NumValue

func (j JSON) NumValue() float64

NumValue returns the golang float64 representation of the json number represented by this JSON struct. If the JSON struct does not represent a json number, this method panics. If in doubt, check with `IsNum()`

func (JSON) ObValue

func (j JSON) ObValue() map[string]interface{}

ObValue returns a golang map[string]interface{} represenation of the json object represented by this JSON struct. If the JSON struct does not represent a json object, this method panics. If in doubt, check with `IsOb()`

func (JSON) RawValue

func (j JSON) RawValue() interface{}

RawValue returns the raw go value of the parsed json, without any type checking

func (JSON) SetElem

func (j JSON) SetElem(index int, value interface{}) error

SetElem sets the element at a given index in this JSON list to the given value. If this JSON object does not represent a list, return an error

func (JSON) SetField

func (j JSON) SetField(fieldName string, val interface{})

SetField updates the field `fieldName` of this JSON object. If this is not a JSON object, we might crash. If the field `fieldName` does not exist on this object, create it.

func (JSON) StringValue

func (j JSON) StringValue() string

StringValue returns the golang string representation of the json string represented by this JSON struct. If the JSON struct does not represent a json string, this method panics. If in doubt, check with `IsString()`

Directories

Path Synopsis
Package gnosj provides gomega matchers for using nosj with the ginkgo and gomega testing libraries: https://github.com/onsi/gomega https://github.com/onsi/ginkgo
Package gnosj provides gomega matchers for using nosj with the ginkgo and gomega testing libraries: https://github.com/onsi/gomega https://github.com/onsi/ginkgo

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL