gabs

package module
v0.0.0-...-4f7cc4b Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2015 License: MIT Imports: 4 Imported by: 4

README

Gabs

Gabs is a small utility for dealing with dynamic or unknown JSON structures in golang. It's pretty much just a helpful wrapper around the golang json.Marshal/json.Unmarshal behaviour and map[string]interface{} objects. It does nothing spectacular except for being fabulous.

https://godoc.org/github.com/Jeffail/gabs

##How to install:

go get github.com/jeffail/gabs

##How to use

###Parsing and searching JSON

...

import "github.com/jeffail/gabs"

jsonParsed, err := gabs.ParseJSON([]byte(`{
	"outter":{
		"inner":{
			"value1":10,
			"value2":22
		},
		"alsoInner":{
			"value1":20
		}
	}
}`))

var value float64
var ok bool

value, ok = jsonParsed.Path("outter.inner.value1").Data().(float64)
// value == 10.0, ok == true

value, ok = jsonParsed.Search("outter", "inner", "value1").Data().(float64)
// value == 10.0, ok == true

value, ok = jsonParsed.Path("does.not.exist").Data().(float64)
// value == 0.0, ok == false

...

###Iterating arrays

...

jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ "first", "second", "third" ]}`))

// S is shorthand for Search
children, _ := jsonParsed.S("array").Children()
for _, child := range children {
	fmt.Println(child.Data().(string))
}

...

Will print:

first
second
third

Children() will return all children of an array in order. This also works on objects, however, the children will be returned in a random order.

###Searching through arrays

If your JSON structure contains arrays you can still search the fields of the objects within the array, this returns a JSON array containing the results for each element.

...

jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ {"value":1}, {"value":2}, {"value":3} ]}`))
fmt.Println(jsonParsed.Path("array.value").String())

...

Will print:

[1,2,3]

###Generating JSON

...

jsonObj := gabs.New()
// or gabs.Consume(jsonObject) to work on an existing map[string]interface{}

jsonObj.Set(10, "outter", "inner", "value")
jsonObj.SetP(20, "outter.inner.value2")
jsonObj.Set(30, "outter", "inner2", "value3")

fmt.Println(jsonObj.String())

...

Will print:

{"outter":{"inner":{"value":10,"value2":20},"inner2":{"value3":30}}}

To pretty-print:

...

fmt.Println(jsonObj.StringIndent("", "  "))

...

Will print:

{
  "outter": {
    "inner": {
      "value": 10,
      "value2": 20
    },
    "inner2": {
      "value3": 30
    }
  }
}

###Generating Arrays

...

jsonObj := gabs.New()

jsonObj.Array("foo", "array")
// Or .ArrayP("foo.array")

jsonObj.ArrayAppend(10, "foo", "array")
jsonObj.ArrayAppend(20, "foo", "array")
jsonObj.ArrayAppend(30, "foo", "array")

fmt.Println(jsonObj.String())

...

Will print:

{"foo":{"array":[10,20,30]}}

###Converting back to JSON

This is the easiest part:

...

jsonParsedObj := gabs.ParseJSON([]byte(`{
	"outter":{
		"values":{
			"first":10,
			"second":11
		}
	},
	"outter2":"hello world"
}`))

jsonOutput := jsonParsedObj.String()
// Becomes `{"outter":{"values":{"first":10,"second":11}},"outter2":"hello world"}`

...

And to serialize a specific segment is as simple as:

...

jsonParsedObj := gabs.ParseJSON([]byte(`{
	"outter":{
		"values":{
			"first":10,
			"second":11
		}
	},
	"outter2":"hello world"
}`))

jsonOutput := jsonParsedObj.Search("outter").String()
// Becomes `{"values":{"first":10,"second":11}}`

...

Documentation

Overview

Package gabs implements a simplified wrapper around creating and parsing JSON.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrOutOfBounds - Index out of bounds.
	ErrOutOfBounds = errors.New("out of bounds")

	// ErrNotObjOrArray - The target is not an object or array type.
	ErrNotObjOrArray = errors.New("not an object or array")

	// ErrNotObj - The target is not an object type.
	ErrNotObj = errors.New("not an object")

	// ErrNotArray - The target is not an array type.
	ErrNotArray = errors.New("not an array")

	// ErrPathCollision - Creating a path failed because an element collided with an existing value.
	ErrPathCollision = errors.New("encountered value collision whilst building path")

	// ErrInvalidInputObj - The input value was not a map[string]interface{}.
	ErrInvalidInputObj = errors.New("invalid input object")

	// ErrInvalidInputText - The input data could not be parsed.
	ErrInvalidInputText = errors.New("input text could not be parsed")

	// ErrInvalidPath - The filepath was not valid.
	ErrInvalidPath = errors.New("invalid file path")
)

Functions

This section is empty.

Types

type Container

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

Container - an internal structure that holds a reference to the core interface map of the parsed json. Use this container to move context.

func Consume

func Consume(root interface{}) (*Container, error)

Consume - Gobble up an already converted JSON object, or a fresh map[string]interface{} object.

func New

func New() *Container

New - Create a new gabs JSON object.

func ParseJSON

func ParseJSON(sample []byte) (*Container, error)

ParseJSON - Convert a string into a representation of the parsed JSON.

func ParseJSONFile

func ParseJSONFile(path string) (*Container, error)

ParseJSONFile - Read a file and convert into a representation of the parsed JSON.

func (*Container) Array

func (g *Container) Array(path ...string) (*Container, error)

Array - Create a new JSON array at a path. Returns an error if the path contains a collision with a non object type.

func (*Container) ArrayAppend

func (g *Container) ArrayAppend(value interface{}, path ...string) error

ArrayAppend - Append a value onto a JSON array.

func (*Container) ArrayAppendP

func (g *Container) ArrayAppendP(value interface{}, path string) error

ArrayAppendP - Append a value onto a JSON array using a dot notation JSON path.

func (*Container) ArrayCount

func (g *Container) ArrayCount(path ...string) (int, error)

ArrayCount - Count the number of elements in a JSON array.

func (*Container) ArrayCountP

func (g *Container) ArrayCountP(path string) (int, error)

ArrayCountP - Count the number of elements in a JSON array using a dot notation JSON path.

func (*Container) ArrayElement

func (g *Container) ArrayElement(index int, path ...string) (*Container, error)

ArrayElement - Access an element from a JSON array.

func (*Container) ArrayElementP

func (g *Container) ArrayElementP(index int, path string) (*Container, error)

ArrayElementP - Access an element from a JSON array using a dot notation JSON path.

func (*Container) ArrayP

func (g *Container) ArrayP(path string) (*Container, error)

ArrayP - Does the same as Array, but using a dot notation JSON path.

func (*Container) ArrayRemove

func (g *Container) ArrayRemove(index int, path ...string) error

ArrayRemove - Remove an element from a JSON array.

func (*Container) ArrayRemoveP

func (g *Container) ArrayRemoveP(index int, path string) error

ArrayRemoveP - Remove an element from a JSON array using a dot notation JSON path.

func (*Container) Children

func (g *Container) Children() ([]*Container, error)

Children - Return a slice of all the children of the array. This also works for objects, however, the children returned for an object will NOT be in order and you lose the names of the returned objects this way.

func (*Container) CountElements

func (g *Container) CountElements(target string) int

CountElements - DEPRECATED: Count the elements of a JSON array, returns -1 if the target is not an array

func (*Container) Data

func (g *Container) Data() interface{}

Data - Return the contained data as an interface{}.

func (*Container) GetElement

func (g *Container) GetElement(target string, index int) *Container

GetElement - DEPRECATED: Get the desired element from a JSON array

func (*Container) Object

func (g *Container) Object(path ...string) (*Container, error)

Object - Create a new JSON object at a path. Returns an error if the path contains a collision with a non object type.

func (*Container) ObjectP

func (g *Container) ObjectP(path string) (*Container, error)

ObjectP - Does the same as Object, but using a dot notation JSON path.

func (*Container) Path

func (g *Container) Path(path string) *Container

Path - Search for a value using dot notation.

func (*Container) Push

func (g *Container) Push(target string, value interface{}) error

Push - DEPRECATED: Push a value onto a JSON array.

func (*Container) RemoveElement

func (g *Container) RemoveElement(target string, index int) error

RemoveElement - DEPRECATED: Remove a value from a JSON array.

func (*Container) S

func (g *Container) S(hierarchy ...string) *Container

S - Shorthand method, does the same thing as Search.

func (*Container) Search

func (g *Container) Search(hierarchy ...string) *Container

Search - Attempt to find and return an object within the JSON structure by specifying the hierarchy of field names to locate the target. If the search encounters an array and has not reached the end target then it will iterate each object of the array for the target and return all of the results in a JSON array.

func (*Container) Set

func (g *Container) Set(value interface{}, path ...string) (*Container, error)

Set - Set the value of a field at a JSON path, any parts of the path that do not exist will be constructed, and if a collision occurs with a non object type whilst iterating the path an error is returned.

func (*Container) SetP

func (g *Container) SetP(value interface{}, path string) (*Container, error)

SetP - Does the same as Set, but using a dot notation JSON path.

func (*Container) String

func (g *Container) String() string

String - Converts the contained object back to a JSON formatted string.

func (*Container) StringIndent

func (g *Container) StringIndent(prefix string, indent string) string

StringIndent - Converts the contained object back to a JSON formatted string with prefix and indent.

Jump to

Keyboard shortcuts

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