gofasion

module
v0.0.0-...-6a05b67 Latest Latest
Warning

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

Go to latest
Published: May 30, 2019 License: MIT

README

GoFasion: A lightweight JSON data parsing library with chained calling style

build codecov go-report

中文文档 | Update Log

Gofasion is a lightweight parsing library that facilitates the parsing of interface JSON data during development. Its biggest feature is to support chained calls, which means that the target key name and key value can be directly obtained without pre-defining the structure of the data.

Open source

https://github.com/Anderson-Lu/gofasion

Required

go 1.9 or above is requried.

Installation

$ go get github.com/Anderson-Lu/gofasion/gofasion

Go module

  1. create go.mod in the root path of your project.
  2. make sure you have enable GO111MODULE by running export GO111MODULE=on
  3. execute go build and you will find all dependencies have been added automatically.
module demo_test/gofasion_demo

require github.com/Anderson-Lu/gofasion v0.0.0-20190311020154-5db4d09c9cb8

How to locate a JSON node

You can think of a JSON data as a tree, each element is a node on the tree (*Fastion), the value of the node can be any type (bool, int etc.), which can be traced from the root node through chained calls. Any node to take out the values.

{
  "level1":{
      "level2":{
          "level3":1
        }
    }
}

To retrieve the value of level3 above, you can quickly access it by the following example:

fsion := gofasion.NewFasion(yourJsonStr)
level3 := fsion.Get("level1").Get("level2").Get("level3").ValueStr()

//or fetch specific value by GetFromPath(dir string) method 
//level3 := fsion.GetFromPath("level1.level2.level3").ValueStr()

How to traverse JSON arrays

We provide the Array() method to represent the JSON data of the array type. For the elements in the array, it is a *Fasion object, which can still be used.

{
  "array" : [
    {"name":1},
    {"name":2}
  ]
}

To traverse the data in array, just do this:

array := fsion.Get("array").Array()
for _,v := range array{
  name := v.Get("name").ValueInt()
  //your code
}

How to traverse irregular JSON data or no key name data

Many times, we need to parse irregular JSON data, such as:

[
  1,2,"helloword",{"name":"demo"}
] 

Can quickly get values ​​by Array() method

Quick start

package main

import (
  "github.com/Anderson-Lu/gofasion/gofasion"
  "fmt"
)

//Rule data
var testJson = `
  {
    "name":"foo",
    "value":1,
    "second_level": {"name":2},
    "second_array":[1,2,3,4,5,6,7],
    "bool": true,
    "value64":1234567890
  }
`

//Irregular data
var testJson2 = `
  [
    1,2,"helloword",{"name":"demo"}
  ]  
`

func main() {
  
  fsion := gofasion.NewFasion(testJson)

  //output "foo"
  fmt.Println(fsion.Get("name").ValueStr())
  
  //output 1
  fmt.Println(fsion.Get("value").ValueInt())
  
  //output {"name":"foo","value":1...}
  fmt.Println(fsion.Json())

  i32 := fsion.Get("value").ValueInt32()
  fmt.Println(i32)

  i64 := fsion.Get("value64").ValueInt64()
  fmt.Println(i64)

  second_fson := fsion.Get("second_level")
  fmt.Println(second_fson.Get("name").ValueStr())

  //Traversal of array data
  second_array := fsion.Get("second_array").Array()
  for _, v := range second_array {
    fmt.Println(v.ValueInt())
  }

  boolVal := fsion.Get("bool").ValueStr()
  fmt.Println(boolVal)

  //Analysis of irregular data
  fsion2 := gofasion.NewFasion(testJson2)
  elems := fsion2.Array()
  fmt.Println(elems[0].ValueInt())
  fmt.Println(elems[1].ValueInt())
  fmt.Println(elems[2].ValueStr())

  fmt.Println(elems[3].Json())

  //Traditional structure analysis
  var iter struct {
    Name  string `json:"name"`
    Value int    `json:"value"`
  }
  fsion.Value(&iter)
  fmt.Println(iter.Name)
  fmt.Println(iter.Value)

  //support check if key str2 exists or not 
  exist, val := root.Get("str2").ValStr()
}

SetJsonParser

In v1.1, or later, we provide a new method SetJson Parser, through which you can customize the JSON parser, such as using this optimized parser library, by setting the following settings, you can replace the default JSON parser with the desired custom parser.

import "github.com/json-iterator/go"

//Parser
gofasion.SetJsonParser(jsoniter.ConfigCompatibleWithStandardLibrary.Marshal,jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal)

Performance

1,000,000 *Fastion.Get() cost about 5,000ms ~ 7,000ms.

Basic methods

  //how to create *Fasion instance
  func NewFasion(rawJson string) *Fasion                              //Create Fasion From raw json
  func NewFasionFromBytes(rawJson []byte) *Fasion                     //Create Fasion From bytes
  func NewFasionFromUrl(targetUrl string, params url.Values) *Fasion  //Create Fasion From http get

  //Methods for *Fasion
  Get(key string) *IFasion         //Get the JSON node object, each node object contains all the methods below
  GetFromPath(dir string) *IFasion //Get the JSON node via node path like node1.node2.node3

  //Methods to get value from *Fasion node
  ValueStr() string                //Get the string value of the node
  ValueInt() int                   //Get the int value of the node
  ValueInt16() int16 
  ValueInt32() int32   
  ValueInt64() int64
  ValueFloat32() float32
  ValueFloat32N(int) float32       //Keep the specified digit value. 
  ValueFloat64() float64
  ValueFloat64N(int) float64       //Keep the specified digit value. 
  ValueBool() bool
  Array() []*Fasion                //Get the array object of the node
  ArrayForEach(func(int, *Fasion)) //Get the array object of the node iterator
  Value(interface{}) error        //Similar to json.Marshal()
  Json() string                   //Get the JSON string of the node
  Keys() []string                 //Get all keys of the node
  HasKey(string) bool             //Judge if the specific node contains specific key

  ValueDefaultStr(string) string  //If not exists, *Fasion will return the specific default value
  ValueDefaultInt(int) int
  ValueDefaultInt16(int16) int16
  ValueDefaultInt32(int32) int32
  ValueDefaultInt64(int64) int64
  ValueDefaultFloat32(float32) float32
  ValueDefaultFloat64(float64) float64
  ValueDefaultBool(bool) bool

  //More option for version 1.11 or higher
  SetJsonParser(customMarshal func(interface{}) ([]byte, error), customUnmarshal func([]byte, interface{}) error)

  //for v1.3 or later version, support check if key exists
  ValStr() (bool, string)
  ValInt64() (bool, int64)
  ValInt32() (bool, int32)
  ValInt16() (bool, int16)
  ValInt() (bool, int)
  ValFloat32() (bool,float32)
  ValFloat32N(int) (bool,float32)
  ValFloat64() (bool,float64)
  ValFloat64N(int) (bool,float64)
  ValBool() (bool,bool)

Version

v1 Basic version, providing common basic functions

Contribution

You are welcome to submit a valuable issue, you can also submit a merger request, hoping to make an open source library for all golang developers.

License

MIT License

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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