• Stars
    star
    49
  • Rank 567,523 (Top 12 %)
  • Language
    Go
  • License
    BSD 3-Clause "New...
  • Created almost 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🧮JSON parser for Go, Support Query and Arithmetic operations.

xjson


Query and Arithmetic

xjson is a JSON parsing library, you can query JSON like OOP.

str := `{"people":{"name":{"first":"bob"}}}`
first := xjson.Get(str, "people.name.first")
assert.Equal(t, first.String(), "bob")
get := xjson.Get(str, "people")
assert.Equal(t, get.String(),`{"name":{"first":"bob"}}`)

Even perform arithmetic operations with JSON.

str := `{"people":[{"bob":{"age":10}},{"alice":{"age":10}}]}`
age := xjson.GetWithArithmetic(str, "people[0].bob.age + people[1].alice.age")
assert.Equal(t, age.Int(), 20)

grammar := `
if ((people[0].bob.age + people[1].alice.age)==20){
	return true
}else{
	return 20
}
`
ret := xjson.GetWithArithmetic(str, grammar)
assert.Equal(t, ret.Bool(), true)

Installing:

go get github.com/crossoverJie/xjson

Query Syntax

  • Use dot . to indicate object nesting relationships.
  • Use [index] indicate an array.
str := `
{
"name": "bob",
"age": 20,
"skill": {
    "lang": [
        {
            "go": {
                "feature": [
                    "goroutine",
                    "channel",
                    "simple",
                    true
                ]
            }
        }
    ]
}
}`

name := xjson.Get(str, "name")
assert.Equal(t, name.String(), "bob")

age := xjson.Get(str, "age")
assert.Equal(t, age.Int(), 20)

assert.Equal(t, xjson.Get(str,"skill.lang[0].go.feature[0]").String(), "goroutine")
assert.Equal(t, xjson.Get(str,"skill.lang[0].go.feature[1]").String(), "channel")
assert.Equal(t, xjson.Get(str,"skill.lang[0].go.feature[2]").String(), "simple")
assert.Equal(t, xjson.Get(str,"skill.lang[0].go.feature[3]").Bool(), true)

// escape
str := `{"1a.":"b"}`
get := Get(str, "1a\\.")
assert.Equal(t, get.String(), "b")

The tow syntax work together to obtain complex nested JSON data.

Arithmetic Syntax

xjson supports + - * / % () arithmetic operations.

str := `{"name":"bob", "age":10,"magic":10.1, "score":{"math":[1,2]}}`
result := xjson.GetWithArithmetic(str, "(age+age)*age+magic")
assert.Equal(t, result.Float(), 210.1)
result = xjson.GetWithArithmetic(str, "(age+age)*age")
assert.Equal(t, result.Int(), 200)

result = xjson.GetWithArithmetic(str, "(age+age) * age + score.math[0]")
assert.Equal(t, result.Int(), 201)

result = xjson.GetWithArithmetic(str, "(age+age) * age - score.math[0]")
assert.Equal(t, result.Int(), 199)

Attention:

  • Only int/float are supported.
  • When other types(string/bool/null..) exist, the empty Result will be returned.
  • When int and float are caculated, float will be returned.

Result

Both Get()/GetWithArithmetic will return Result type.

It provides the following methods to help us obtain data more easily.

func (r Result) String() string
func (r Result) Bool() bool
func (r Result) Int() int
func (r Result) Float() float64
func (r Result) Map() map[string]interface{}
func (r Result) Array() []interface{}
func (r Result) Exists() bool

You can tell what they mean from their names.

Other APIs

Decode

It can convert JSON strings to interface{}.

func TestJson(t *testing.T) {
	str := `{
   "glossary": {
       "title": "example glossary",
		"age":1,
		"long":99.99,
		"GlossDiv": {
           "title": "S",
			"GlossList": {
               "GlossEntry": {
                   "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                       "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML", true, null]
                   },
					"GlossSee": "markup"
               }
           }
       }
   }
}`
	decode, err := xjson.Decode(str)
	assert.Nil(t, err)
	fmt.Println(decode)
	v := decode.(map[string]interface{})
	glossary := v["glossary"].(map[string]interface{})
	assert.Equal(t, glossary["title"], "example glossary")
	assert.Equal(t, glossary["age"], 1)
	assert.Equal(t, glossary["long"], 99.99)
	glossDiv := glossary["GlossDiv"].(map[string]interface{})
	assert.Equal(t, glossDiv["title"], "S")
	glossList := glossDiv["GlossList"].(map[string]interface{})
	glossEntry := glossList["GlossEntry"].(map[string]interface{})
	assert.Equal(t, glossEntry["ID"], "SGML")
	assert.Equal(t, glossEntry["SortAs"], "SGML")
	assert.Equal(t, glossEntry["GlossTerm"], "Standard Generalized Markup Language")
	assert.Equal(t, glossEntry["Acronym"], "SGML")
	assert.Equal(t, glossEntry["Abbrev"], "ISO 8879:1986")
	glossDef := glossEntry["GlossDef"].(map[string]interface{})
	assert.Equal(t, glossDef["para"], "A meta-markup language, used to create markup languages such as DocBook.")
	glossSeeAlso := glossDef["GlossSeeAlso"].(*[]interface{})
	assert.Equal(t, (*glossSeeAlso)[0], "GML")
	assert.Equal(t, (*glossSeeAlso)[1], "XML")
	assert.Equal(t, (*glossSeeAlso)[2], true)
	assert.Equal(t, (*glossSeeAlso)[3], "")
	assert.Equal(t, glossEntry["GlossSee"], "markup")
}

Features

  • Support syntax: xjson.Get("glossary.title")
  • Support arithmetic operators: xjson.Get("glossary.age+long")
  • Support escape.
  • Resolve to struct

Acknowledgements

gjson

gscript

More Repositories

1

JCSprout

👨‍🎓 Java Core Sprout : basic, concurrent, algorithm
Java
27,060
star
2

cim

📲cim(cross IM) 适用于开发者的分布式即时通讯系统
Java
9,095
star
3

SSM

💕 build SSM from 0 👉🏽👉🏽 distributed micro service.
Java
3,441
star
4

distributed-redis-tool

🔒A simple distributed tools based on Redis.
Java
608
star
5

springboot-cloud

👬 springboot + springcloud build micro service
Java
481
star
6

ptg

💥Performance testing tool (Go), It is also a GUI gRPC client.
Go
320
star
7

gscript

💪🏻This is a statically and strongly typed language written in Go.|GScript 是用 Go 编写的静态、强类型的脚本语言。
Go
209
star
8

blog.toolbox

博客工具箱(字数统计、图片备份、图床批量替换)
Java
116
star
9

feign-plus

A better feign client library to combine with SpringBoot.
Java
71
star
10

leetcode

🕵️‍♂️ leetcode practice
Java
51
star
11

k8s-combat

☸️适用于研发人员的 k8s 实战项目🐳
Go
38
star
12

SSM-DUBBO-HTTP

💥 dubbo provide HTTP service
Java
27
star
13

SSM-DUBBO-FILTER

💋 dubbo日志扩展插件
Java
24
star
14

company_open

a personal forum
Java
21
star
15

netty-learning

netty 学习记录
Java
19
star
16

SSM-CONSUMER

⚡ dubbo consumer
Java
19
star
17

btb

☄️ A cli tool for blog toolbox.
Go
18
star
18

gorm-optimistic

This is an optimistic lock plugin based on GORM.
Go
15
star
19

blog-post

博客备份
12
star
20

crossoverJie.github.io

personal blog
HTML
11
star
21

SSM-REQUEST-CHECK

⏳ 基于annotation的http请求去重插件
Java
10
star
22

sqlalchemy-transfer

A plugin that can help you transfer MySQL DDL to sqlalchemy-model.
Java
9
star
23

sales-store

Base of B2B
Java
7
star
24

gscript-homepage

GScript homepage
Vue
5
star
25

crossoverJie

3
star
26

crossoverjie-index

个人主页
JavaScript
2
star
27

java-noob

Java
2
star
28

crossWeather

自学Android不久之后独立开发的Android项目—crossWeather
Java
2
star
29

pulsar-biz-test

1
star
30

easyframe-msg

Msg Producer and Consumer, a wrapper of Kafka
Java
1
star