jsonic

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2021 License: MIT Imports: 5 Imported by: 0

README

JSONIC

GoDoc Release Report Coverage Status

Jsonic is the complete set of utilities to handle json data. There's no need to define structs anymore. It's completely safe to perform nested queries in the JSON. The strong typed methods part of this library will help you have the desired result without writing any extra code.

Installation

go get github.com/sinhashubham95/jsonic

Understanding the query path

Jsonic uses a unique and simple way to query the elements in a json. It's easy but unique, so you need to understand the same for using Jsonic.

Consider the following json.

{
  "a": {
    "x": "p",
    "arr": [
      {
        "a": "b",
        "c.d": {
          "e": "f"
        }
      }
    ]
  },
  "c": "d",
  "a.x": {
    "y": "q"
  },
  "a.x.y": {
    "z": "r"
  }
}

Though, practically such a JSON won't exist, but still Jsonic is intelligent enough to handle even this. Go through the below table carefully and it will help you understand the path schema.

Path Result Comments
{EMPTY_STRING} entire json empty string returns the entire json if no empty string exists in the key
. entire json dot returns the entire json if no dot exists in the key
a {"x": "p", "arr": [{ "a": "b", "c.d": { "e": "f" } }]} it returns the entire json tree of a
a.x p multiple options here, but the first preference goes to the tree of a
a.x.y q multiple options here, the first preference will be given to a.x
a.x.y.z r there is only a single possibility here
a.arr [{ "a": "b", "c.d": { "e": "f" } }] it returns the entire array denoting the json tree of a.arr
a.arr[0] { "a": "b", "c.d": { "e": "f" } } it returns the first element of the array
a.arr[0].a b it returns the element for key a of the first element of array
a.arr[0].c.d.e f

As you would have understood, if there are multiple JSON trees satisfying the path, and the path looks something like this a.b.c.d, then the preferences will be in the following order - a > a.b > a.b.c > a.b.c.d.

Consider another json.

{
  "": "a",
  ".": "b"
}

Here the paths resolve in a different manner.

Path Result Comments
{EMPTY_STRING} a empty string returns the entire json if no empty string exists in the key
. b empty string returns the entire json if no empty string exists in the key

How to Use?

Jsonic allows you to process the JSON bytes. You can create a new instance of Jsonic for every JSON you have and you can get the child JSON trees using the set of utilities it provides.

Create a New Instance

This will create a new instance using the JSON bytes provided as it's data to be used on.

import (
  "github.com/sinhashubham95/jsonic"
)

func New() {
  json := "{\"naruto\": \"rocks\"}"
  j, err := jsonic.New([]byte(json))
  // perform any sort of operations on the json using the instance created
}
Create a child instance

On the Jsonic created, you can provide a child path and get a new instance with the child JSON tree satisfying the path provided as it's data.

import (
  "github.com/sinhashubham95/jsonic"
)

func Child() {
  json := "{\"naruto\": \"rocks\"}"
  j, err := jsonic.New([]byte(json))
  if err != nil {
    return
  }
  
  // create a child
  child, err := jsonic.Child("naruto")
  // now if you want to query on the child then use this child instance
}
Get the data at the path

On the Jsonic created, you can get the data at the path specified.

import (
  "github.com/sinhashubham95/jsonic"
)

func Get() {
  json := "{\"naruto\": \"rocks\"}"
  j, err := jsonic.New([]byte(json))
  if err != nil {
    return
  }
  
  // get the data
  data, err := jsonic.Get("naruto")
  // this data will have type interface{} with value "rocks"
}
Get typed data at the path

Though using structs is not required with the wonderful set of utilities Jsonic provides, but even if you like to use that, it is very simple to get your result cast into the struct you want.

import (
  "github.com/sinhashubham95/jsonic"
)

type Detail struct {
  Name string `json:"name"`
}

func GetTyped() {
  json := "{\"characters\": [{\"name\": \"naruto\"}, {\"name\": \"boruto\"}]}"
  j, err := jsonic.New([]byte(json))
  if err != nil {
    return
  }
  
  // get the data
  var data []Detail
  err := jsonic.GetTyped("characters", &data)
  // this data will contain 2 elements with names as naruto and boruto
}
Other Typed Utilities

Apart from the generic query methods mentioned above, Jsonic contains a bunch of others.

import (
  "github.com/sinhashubham95/jsonic"
)

func OtherGetters(j *Jsonic, path string) {
  // primitives
  i, err := j.GetInt(path)                    // int
  i64, err := j.GetInt64(path)                // int64
  f, err := j.GetFloat(path)                  // float32
  f64, err := j.GetFloat64(path)              // float64
  b, err := j.GetBool(path)                   // bool
  s, err := j.GetString(path)                 // string

  // arrays
  a, err := j.GetArray(path)                  // []interface{}
  iArr, err := j.GetIntArray(path)            // []int
  i64Arr, err := j.GetInt64Array(path)        // []int64
  fArr, err := j.GetFloatArray(path)          // []float32
  f64Arr, err := j.GetFloat64Array(path)      // []float64
  bArr, err := j.GetBoolArray(path)           // []bool
  sArr, err := j.GetStringArray(path)         // []string

  // maps
  m, err := j.GetMap(path)                    // map[string]interface{}
  iMap, err := j.GetIntMap(path)              // map[string]int
  i64Map, err := j.GetInt64Map(path)          // map[string]int64
  fMap, err := j.GetFloatMap(path)            // map[string]float32
  f64Map, err := j.GetFloat64Map(path)        // map[string]float64
  bMap, err := j.GetBoolMap(path)             // map[string]bool
  sMap, err := j.GetStringMap(path)           // map[string]string
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUnexpectedJSONData = errors.New("unexpected json data provided, neither array nor object")
	ErrIndexNotFound      = errors.New("expected index for json array but found something else")
	ErrIndexOutOfBound    = errors.New("index out of bounds of the json array")
	ErrNoDataFound        = errors.New("no tree satisfies the path elements provided")
	ErrInvalidType        = errors.New("data at the specified path does not match the expected type")
)

errors

Functions

This section is empty.

Types

type Jsonic

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

Jsonic is the type to hold the JSON data

func New

func New(data []byte) (*Jsonic, error)

New is used to crete a new parser for the JSON data

func (*Jsonic) Child

func (j *Jsonic) Child(path string) (*Jsonic, error)

Child returns the json tree at the path specified.

It returns an error in case there is nothing that can be resolved at the specified path.

Path should be like this for example - a.[0].b, [0].a.b, etc. The path elements should be separated with dots. Now the path elements can either be the index in case of an array with the index enclosed within square brackets or it can be the key of the object.

func (*Jsonic) Get

func (j *Jsonic) Get(path string) (interface{}, error)

Get is used to get the data at the path specified.

func (*Jsonic) GetArray

func (j *Jsonic) GetArray(path string) ([]interface{}, error)

GetArray is used to get the data array at the path specified.

func (*Jsonic) GetBool

func (j *Jsonic) GetBool(path string) (bool, error)

GetBool is used to get the integer at the path specified.

func (*Jsonic) GetBoolArray

func (j *Jsonic) GetBoolArray(path string) ([]bool, error)

GetBoolArray is used to get the boolean array at the path specified.

func (*Jsonic) GetBoolMap

func (j *Jsonic) GetBoolMap(path string) (map[string]bool, error)

GetBoolMap is used to get the boolean map at the path specified.

func (*Jsonic) GetFloat

func (j *Jsonic) GetFloat(path string) (float32, error)

GetFloat is used to get the floating point number at the path specified.

func (*Jsonic) GetFloat64

func (j *Jsonic) GetFloat64(path string) (float64, error)

GetFloat64 is used to get the floating point number at the path specified.

func (*Jsonic) GetFloat64Array

func (j *Jsonic) GetFloat64Array(path string) ([]float64, error)

GetFloat64Array is used to get the 64-bit floating point number array at the path specified.

func (*Jsonic) GetFloat64Map

func (j *Jsonic) GetFloat64Map(path string) (map[string]float64, error)

GetFloat64Map is used to get the 64-bit floating point number map at the path specified.

func (*Jsonic) GetFloatArray

func (j *Jsonic) GetFloatArray(path string) ([]float32, error)

GetFloatArray is used to get the floating point number array at the path specified.

func (*Jsonic) GetFloatMap

func (j *Jsonic) GetFloatMap(path string) (map[string]float32, error)

GetFloatMap is used to get the floating point number map at the path specified.

func (*Jsonic) GetInt

func (j *Jsonic) GetInt(path string) (int, error)

GetInt is used to get the integer at the path specified.

func (*Jsonic) GetInt64

func (j *Jsonic) GetInt64(path string) (int64, error)

GetInt64 is used to get the integer at the path specified.

func (*Jsonic) GetInt64Array

func (j *Jsonic) GetInt64Array(path string) ([]int64, error)

GetInt64Array is used to get the 64-bit integer array at the path specified.

func (*Jsonic) GetInt64Map

func (j *Jsonic) GetInt64Map(path string) (map[string]int64, error)

GetInt64Map is used to get the 64-bit integer map at the path specified.

func (*Jsonic) GetIntArray

func (j *Jsonic) GetIntArray(path string) ([]int, error)

GetIntArray is used to get the integer array at the path specified.

func (*Jsonic) GetIntMap

func (j *Jsonic) GetIntMap(path string) (map[string]int, error)

GetIntMap is used to get the integer map at the path specified.

func (*Jsonic) GetMap

func (j *Jsonic) GetMap(path string) (map[string]interface{}, error)

GetMap is used to get the data map at the path specified.

func (*Jsonic) GetString

func (j *Jsonic) GetString(path string) (string, error)

GetString is used to get the string at the path specified.

func (*Jsonic) GetStringArray

func (j *Jsonic) GetStringArray(path string) ([]string, error)

GetStringArray is used to get the string array at the path specified.

func (*Jsonic) GetStringMap

func (j *Jsonic) GetStringMap(path string) (map[string]string, error)

GetStringMap is used to get the string map at the path specified.

func (*Jsonic) GetTyped added in v1.1.0

func (j *Jsonic) GetTyped(path string, val interface{}) error

GetTyped is used to get the data at the path specified in the value provided. this value can be of any type, but preferably use a struct using it with primitives will return an error note that here a pointer should be used as value

Jump to

Keyboard shortcuts

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