fson

package module
v0.0.0-...-759d8fb Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2020 License: MIT Imports: 4 Imported by: 0

README

fson logo

Documentation Go Report Card

Fson is a simple library for working with arbitrary JSON data of unknown structure. One of the key reasons for creating this were to add two critical features for my use cases. First was an Fmap function for easily applying a function to the JSON data structure and secondly, provide a interface type for dealing with Postgresql's JSON(b) types and that types encoding to JSON for our REST api.

Usage

Import package

import (
	"github.com/kgwinnup/fson"
)

Basic example of interacting with a JSON structure

package main

import (
	"fmt"
	"github.com/kgwinnup/fson"
)

func main() {
	//receive some byte array and create an Fson object
	data := []byte(`{
        "foo": 1, 
        "foo2": { 
                    "bar": 1, 
                    "baz": [1,1,1]
                }
        }`)
	fsonobj := fson.New(data)

	// print the JSON string
	fmt.Println(fsonobj)

	// Get a value from the JSON
	if val, ok := fsonobj.Get("foo2", "bar"); ok {
		//add 100 to our new value
		newVal := val.(float64) + 100

		//set the new value back in the JSON structure
		// the last bool parameter, if true, will turn the value in the key to an array
		fsonobj.Set(newVal, "foo2", "bar")
		fmt.Println(fsonobj)
	}

}

Output:

{"foo":1,"foo2":{"bar":1,"baz":[1,1,1]}}
{"foo":1,"foo2":{"bar":101,"baz":[1,1,1]}}

Using generic "functional" functions

Fmap

Fmap will apply a function to every value in the JSON while leaving the underlying JSON structure unchanged. Only the values are mutated, mutation is in place.

import (
	"fmt"
	"github.com/kgwinnup/fson"
)

func main() {
    data := []byte(`{
		"foo": 1, 
		"foo2": {
			"bar": 1, 
			"baz": [1,1,1]
			}
		}`)
	out := fson.New(data)

	out.Fmap(func(v interface{}) interface{} {
		switch v.(type) {
		case float64:
			return v.(float64) + 1
		default:
			return v.(int) + 1
		}
	})

	fmt.Println(out)
}

Output {"foo":2,"foo2":{"bar":2,"baz":[2,2,2]}}

Filter

Filter will remove values that do not match the FilterFn. This function will change the underlying JSON structure.

import (
	"fmt"
	"github.com/kgwinnup/fson"
)

func main() {
    data := []byte(`{
		"foo": 2, 
		"foo2": {
			"bar": 1, 
			"baz": [2,1,1]
			}
		}`)
	out := fson.New(data)

	out.Filter(func(v interface{}) bool {
		switch v.(type) {
		case float64:
			if v.(float64) > 1 {
				return false
			} else {
				return true
			}
		default:
			return true
		}
	})

	fmt.Println(out)
}

Output {"foo2":{"bar":1,"baz":[1,1]}}

Usage with Postgresql's JSON types

For it to work with JSON types, the Scan interface is provided as well as a Bytes method.

import (
	"fmt"
	"github.com/kgwinnup/fson"
    "database/sql"
    _ "github.com/lib/pq"
)

type TableStruct struct {
    ItemId int64
    ItemDescription string
    ItemData *fson.Fson
}

To insert or update any JSON field, you must convert the value to a []byte array within the query.

s := TableStruct{1, "description", fson.New([]byte{`{"foo": "bar"}`})}
_, err := db.Query(`insert into table(itemdescription, itemdata) values($1, $2)`, s.ItemDescription, s.ItemData.Bytes())

Getting serialized into your structure is just using the row.Scan method as you normally would.

var tbl TableStruct
row := db.QueryRow(`select * from myTable where ItemId = 1;`)
err := row.Scan(&tbl.ItemId, &tbl.ItemDescription, &tbl.ItemData)

Documentation

Overview

Package fson provides a way to interact with arbitrary JSON fields as well as use JSON(b) within Postgresql Fson supports the json interfaces MarshalJSON/UnmarshalJSON as well as the Scan interface within the db packages

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FilterFn

type FilterFn func(interface{}) bool

FilterFn is the interface returning a boolean value of whether to include this value. This will change the JSON structure

type FmapFn

type FmapFn func(interface{}) interface{}

FmapFn will transform a value within the JSON into a new value, leaving the JSON structure alone

type Fson

type Fson struct {
	Data map[string]interface{}
}

Fson struct is the core structure, no exported members

func FromFile

func FromFile(path string) (*Fson, error)

FromFile will load a JSON object from a file

func New

func New(b []byte) *Fson

New initializes a new Fson object given a JSON byte slice

func ParseJSON

func ParseJSON(b []byte) (*Fson, error)

ParseJSON takes some bytes and parses it into an Fson object

func (*Fson) Bytes

func (f *Fson) Bytes() []byte

Bytes will return a byte slice of the underlying JSON data. If there is an error an empty byte slice is returned

func (*Fson) Del

func (f *Fson) Del(path []string)

Del will delete a key from the JSON object

func (*Fson) Exists

func (f *Fson) Exists(path ...string) bool

Exists will return true if the key exists in the JSON

func (*Fson) Filter

func (f *Fson) Filter(fn FilterFn)

Filter will filter out values from the JSON where the f "filterFn" returns false for that value

func (*Fson) Fmap

func (f *Fson) Fmap(fn FmapFn)

Fmap applys a function to every value in the JSON structure, mutating them in place

func (*Fson) Get

func (f *Fson) Get(path ...string) (interface{}, bool)

Get works like set in that the path to the key is specified as a list of string values which represent the orderd nested object keys

func (*Fson) GetArray

func (f *Fson) GetArray(path ...string) ([]interface{}, bool)

GetArray will retrieve an array item from a specific key in the Fson object. The JSON array will be returned as a slice of interface{}

func (*Fson) GetBool

func (f *Fson) GetBool(path ...string) (bool, bool)

GetBool will check if the key exists, and if the key is an bool it will return it

func (*Fson) GetFloat

func (f *Fson) GetFloat(path ...string) (float64, bool)

GetFloat will check if the key exists, and if the key is an float64 it will return it

func (*Fson) GetInt

func (f *Fson) GetInt(path ...string) (int, bool)

GetInt will check if the key exists, and if the key is an integer it will return it

func (*Fson) GetObject

func (f *Fson) GetObject(path ...string) (*Fson, bool)

GetObject will work the same as Get except this will automatically encode the result into an Fson object. If the value retrieved is not a JSON object, this will return nil, false

func (*Fson) GetString

func (f *Fson) GetString(path ...string) (string, bool)

GetString will check if the key exists and if the key is a string, if so, returns the (string, true), else ("", false)

func (*Fson) Loads

func (f *Fson) Loads(b []byte) error

Loads will take nil or a []byte array and create a Fson object with it. Generally nil is used if you want to build your JSON object from scratch with the Set method This will overwrite any current data that is in the Fson object

func (*Fson) MarshalJSON

func (f *Fson) MarshalJSON() ([]byte, error)

MarshalJSON implementation for JSON encoding

func (*Fson) Merge

func (f *Fson) Merge(obj *Fson)

Merge will take two an Fson object and merge it with an existing Fson object. The new object will overwrite any matching key values

func (*Fson) Pretty

func (f *Fson) Pretty() string

Pretty returns a prety printed string of the underlying JSON

func (*Fson) Scan

func (f *Fson) Scan(src interface{}) error

Scan will take a pointer interface and attempt to decode as Fson structure

func (*Fson) Set

func (f *Fson) Set(value interface{}, path ...string)

Set will set a value to a specified path. The path is defined as a variadic parameter. This will overwrite any value that is located at the provided key

func (*Fson) SetA

func (f *Fson) SetA(value interface{}, path ...string)

SetA is the same as set except that it will append to a list. If no list exists, it will create a list. If an element currently exists, a new list will be created with the existing element as the head of the list.

func (*Fson) String

func (f *Fson) String() string

String converts the Fson object into a string

func (*Fson) UnmarshalJSON

func (f *Fson) UnmarshalJSON(b []byte) error

UnmarshalJSON impelmentation for JSON decoding to Fson

Jump to

Keyboard shortcuts

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