Get JSON values quickly - JSON Parser for Go
项目地址
https://github.com/tidwall/gjson
安装
$ go get -u github.com/tidwall/gjson
官方的性能测试
Benchmarks of GJSON alongside encoding/json, ffjson, EasyJSON, jsonparser, and json-iterator
BenchmarkGJSONGet-8 3000000 372 ns/op 0 B/op 0 allocs/op
BenchmarkGJSONUnmarshalMap-8 900000 4154 ns/op 1920 B/op 26 allocs/op
BenchmarkJSONUnmarshalMap-8 600000 9019 ns/op 3048 B/op 69 allocs/op
BenchmarkJSONDecoder-8 300000 14120 ns/op 4224 B/op 184 allocs/op
BenchmarkFFJSONLexer-8 1500000 3111 ns/op 896 B/op 8 allocs/op
BenchmarkEasyJSONLexer-8 3000000 887 ns/op 613 B/op 6 allocs/op
BenchmarkJSONParserGet-8 3000000 499 ns/op 21 B/op 0 allocs/op
BenchmarkJSONIterator-8 3000000 812 ns/op 544 B/op 9 allocs/op
一些使用的demo
官方demo
package main
import "github.com/tidwall/gjson"
const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
func main() {
value := gjson.Get(json, "name.last")
println(value.String())
}
自己写的一个demo
package main
import (
"fmt"
"github.com/tidwall/gjson"
)
var j = `
{
"code": 0,
"msg": "success",
"stime": "2019-04-10 21:52:51",
"body": {
"data": {
"out_trade_no": "WXP20190410215250007305",
"pay": {
"appid": "wx822ef833b63acd132",
"partnerid": "1525575431",
"prepayid": "wx10215251062790766be893d11817189886",
"package": "Sign=WXPay",
"noncestr": "ls6k1hh2gdnyxxvi7hvs",
"timestamp": "1554904371",
"sign": "DFB92DF45CCA01DEF46E9BB2DB8BB630"
}
}
}
}
`
func main() {
mp := gjson.Get(j, "body.data.pay")
fmt.Println(mp.Map())
str := gjson.Get(j, "body.data.pay.sign")
fmt.Println(str.String())
fmt.Println(gjson.Get(j, "stime").String())
}
返回信息
map[appid:wx822ef833b63acd132 partnerid:1525575771 prepayid:wx10215251062790766be893d11817189886 package:Sign=WXPay noncestr:ls6k1hh2gdnyxxvi7hvs t
imestamp:1554904371 sign:DFB92DF45CCA01DEF46E9BB2DB8BB630]
DFB92DF45CCA01DEF46E9BB2DB8BB630
2019-04-10 21:52:51