json

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2022 License: MIT Imports: 7 Imported by: 0

README

A Simple JSON Reader

A library for dynamically inspecting parsed JSON values rather than for data binding or serialization.

Uses a table-driven parser based on Doug Crockford's json-c JSON Checker C library / command line utility. This should lead to a fairly fast parsing time, though that's not guaranteed and isn't even a design goal.

See the godoc for the full API.

Installation

go get -u github.com/mcvoid/json

Usage example

Taken from example_test.go

import "github.com/mcvoid/json"

...

func TestUsage(t *testing.T) {
	// use one of the ParseXXX functions to get a JSON value from text.
	// You can pass in strings, []byte, or io.Reader.
	val, err := json.ParseString(`
	{
		"null": null,
		"integer": 5,
		"number": 5.0,
		"boolean": true,
		"array": [null, 5, 5.0, true],
		"object": {}
	}
	`)
	if err != nil {
		t.Error("Can't parse json... somehow.")
	}

	// to inspect the type, use the Type method.
	if val.Type() != json.Object {
		t.Error("JSON object is wrong type!")
	}

	// Objects can be extracted as maps of values
	m, _ := val.AsObject()
	if m["null"].Type() != json.Null {
		t.Error("JSON null is wrong type!")
	}

	// We differentiate integers and numbers, but integers count as numbers, too.
	// Integer is mainly there for large whole numbers that float64 might
	// not have the precision for.
	i, _ := m["integer"].AsNumber()
	n, _ := m["number"].AsNumber()
	if i != n {
		t.Error("It works this time, but this isn't the best way to check for floating point equivalency, btw")
	}

	// Arrays are represented as slices of JSON values.
	a, _ := m["array"].AsArray()

	// Booleans are bools.
	b, _ := a[3].AsBoolean()
	if !b {
		t.Error("true... isn't?")
	}

	// Key and value allow for a fluent interface to drill down to values.
	beatles, _ := json.ParseString(`{
		"name": "The Beatles",
		"type": "band",
		"members": [
			{
				"name": "John",
				"role": "guitar"
			},
			{
				"name": "Paul",
				"role": "bass"
			},
			{
				"name": "George",
				"role": "guitar"
			},
			{
				"name": "Ringo",
				"role": "drums"
			}
		]
	}`)

	name, _ := beatles.Key("members").Index(2).Key("name").AsString()
	fmt.Println(name) //  "George"

	// Drilling down using the fluent interface over invalid values or missing keys
	// will just propagate a null value.

	null := beatles.Key("something").Index(-1).Key("")
	fmt.Println(null) //  "null"

	// And that's all there is to it. Enjoy!
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// A value is trying to be cast to an incorrect type.
	ErrType = errors.New("type error")
	// A problem occured while parsing the JSON
	ErrParse = errors.New("parse error")
)

Functions

This section is empty.

Types

type Type

type Type int

The type of a JSON value.

const (
	Null Type = iota
	Number
	Integer
	String
	Boolean
	Array
	Object
)

Possible JSON values

func (Type) String

func (t Type) String() string

Returns a string representation of a JSON Type.

type Value

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

A structured JSON value

func Parse

func Parse(r io.Reader) (*Value, error)

Parses a JSON value from a Reader. If it cannot read a valid value, it returns a null value and a non-nil error. Returns the parsed value and nil error otherwise.

func ParseBytes

func ParseBytes(b []byte) (*Value, error)

Parses a JSON value from a byte slice. If it cannot read a valid value, it returns a null value and a non-nil error. Returns the parsed value and nil error otherwise.

func ParseString

func ParseString(s string) (*Value, error)

Parses a JSON value from a string. If it cannot read a valid value, it returns a null value and a non-nil error. Returns the parsed value and nil error otherwise.

func (*Value) AsArray

func (v *Value) AsArray() ([]*Value, error)

Extracts an array value from the JSON. Returns ErrType if the value is not array, nil otherwise.

func (*Value) AsBoolean

func (v *Value) AsBoolean() (bool, error)

Extracts a boolean value from the JSON. Returns ErrType if the value is not boolean, nil otherwise.

func (*Value) AsInteger

func (v *Value) AsInteger() (int64, error)

Extracts an integer from the JSON. Will not convert decimal to integer. If decimal precision is needed, use AsNumber instead. Returns ErrType if the value is niether a number nor an integer. Returns nil otherwise.

func (*Value) AsNull

func (v *Value) AsNull() (struct{}, error)

Extracts a null value from the JSON. Returns ErrType if the value is not null, nil otherwise.

func (*Value) AsNumber

func (v *Value) AsNumber() (float64, error)

Extracts a number from the JSON. If the value is an integer, it is cast to a float64. If integer precision is needed, use AsInteger instead. Returns ErrType if the value is niether a number nor an integer. Returns nil otherwise.

func (*Value) AsObject

func (v *Value) AsObject() (map[string]*Value, error)

Extracts an object value from the JSON. Returns ErrType if the value is not object, nil otherwise.

func (*Value) AsString

func (v *Value) AsString() (string, error)

Extracts a string value from the JSON. Returns ErrType if the value is not string, nil otherwise.

func (*Value) Index added in v1.1.0

func (v *Value) Index(i int) *Value

Fluent interface for accessing array members. If the value is not an array, or the index is out of range, it instead returns null.

func (*Value) Key added in v1.1.0

func (v *Value) Key(k string) *Value

Fluent interface for accessing object members. If the value is not an object, or the key doesn't exist, it instead returns null.

func (*Value) String

func (v *Value) String() string

Returns a string representation of the values. NOT valid JSON!

func (*Value) Type

func (v *Value) Type() Type

Gets the type of the current value.

Jump to

Keyboard shortcuts

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