Giter Site home page Giter Site logo

gjson's Introduction

GJSON
GoDoc GJSON Playground GJSON Syntax

get json values quickly

GJSON is a Go package that provides a fast and simple way to get values from a json document. It has features such as one line retrieval, dot notation paths, iteration, and parsing json lines.

Also check out SJSON for modifying json, and the JJ command line tool.

This README is a quick overview of how to use GJSON, for more information check out GJSON Syntax.

GJSON is also available for Python and Rust

Getting Started

Installing

To start using GJSON, install Go and run go get:

$ go get -u github.com/tidwall/gjson

This will retrieve the library.

Get a value

Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.

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())
}

This will print:

Prichard

There's also the GetMany function to get multiple values at once, and GetBytes for working with JSON byte slices.

Path Syntax

Below is a quick overview of the path syntax, for more complete information please check out GJSON Syntax.

A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard characters can be escaped with '\'.

{
  "name": {"first": "Tom", "last": "Anderson"},
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},
    {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]},
    {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]}
  ]
}
"name.last"          >> "Anderson"
"age"                >> 37
"children"           >> ["Sara","Alex","Jack"]
"children.#"         >> 3
"children.1"         >> "Alex"
"child*.2"           >> "Jack"
"c?ildren.0"         >> "Sara"
"fav\.movie"         >> "Deer Hunter"
"friends.#.first"    >> ["Dale","Roger","Jane"]
"friends.1.last"     >> "Craig"

You can also query an array for the first match by using #(...), or find all matches with #(...)#. Queries support the ==, !=, <, <=, >, >= comparison operators and the simple pattern matching % (like) and !% (not like) operators.

friends.#(last=="Murphy").first    >> "Dale"
friends.#(last=="Murphy")#.first   >> ["Dale","Jane"]
friends.#(age>45)#.last            >> ["Craig","Murphy"]
friends.#(first%"D*").last         >> "Murphy"
friends.#(first!%"D*").last        >> "Craig"
friends.#(nets.#(=="fb"))#.first   >> ["Dale","Roger"]

Please note that prior to v1.3.0, queries used the #[...] brackets. This was changed in v1.3.0 as to avoid confusion with the new multipath syntax. For backwards compatibility, #[...] will continue to work until the next major release.

Result Type

GJSON supports the json types string, number, bool, and null. Arrays and Objects are returned as their raw json types.

The Result type holds one of these:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON string literals
nil, for JSON null

To directly access the value:

result.Type           // can be String, Number, True, False, Null, or JSON
result.Str            // holds the string
result.Num            // holds the float64 number
result.Raw            // holds the raw json
result.Index          // index of raw value in original json, zero means index unknown
result.Indexes        // indexes of all the elements that match on a path containing the '#' query character.

There are a variety of handy functions that work on a result:

result.Exists() bool
result.Value() interface{}
result.Int() int64
result.Uint() uint64
result.Float() float64
result.String() string
result.Bool() bool
result.Time() time.Time
result.Array() []gjson.Result
result.Map() map[string]gjson.Result
result.Get(path string) Result
result.ForEach(iterator func(key, value Result) bool)
result.Less(token Result, caseSensitive bool) bool

The result.Value() function returns an interface{} which requires type assertion and is one of the following Go types:

boolean >> bool
number  >> float64
string  >> string
null    >> nil
array   >> []interface{}
object  >> map[string]interface{}

The result.Array() function returns back an array of values. If the result represents a non-existent value, then an empty array will be returned. If the result is not a JSON array, the return value will be an array containing one result.

64-bit integers

The result.Int() and result.Uint() calls are capable of reading all 64 bits, allowing for large JSON integers.

result.Int() int64    // -9223372036854775808 to 9223372036854775807
result.Uint() uint64   // 0 to 18446744073709551615

Modifiers and path chaining

New in version 1.2 is support for modifier functions and path chaining.

A modifier is a path component that performs custom processing on the json.

Multiple paths can be "chained" together using the pipe character. This is useful for getting results from a modified query.

For example, using the built-in @reverse modifier on the above json document, we'll get children array and reverse the order:

"children|@reverse"           >> ["Jack","Alex","Sara"]
"children|@reverse|0"         >> "Jack"

There are currently the following built-in modifiers:

  • @reverse: Reverse an array or the members of an object.
  • @ugly: Remove all whitespace from a json document.
  • @pretty: Make the json document more human readable.
  • @this: Returns the current element. It can be used to retrieve the root element.
  • @valid: Ensure the json document is valid.
  • @flatten: Flattens an array.
  • @join: Joins multiple objects into a single object.
  • @keys: Returns an array of keys for an object.
  • @values: Returns an array of values for an object.
  • @tostr: Converts json to a string. Wraps a json string.
  • @fromstr: Converts a string from json. Unwraps a json string.
  • @group: Groups arrays of objects. See e4fc67c.
  • @dig: Search for a value without providing its entire path. See e8e87f2.

Modifier arguments

A modifier may accept an optional argument. The argument can be a valid JSON document or just characters.

For example, the @pretty modifier takes a json object as its argument.

@pretty:{"sortKeys":true} 

Which makes the json pretty and orders all of its keys.

{
  "age":37,
  "children": ["Sara","Alex","Jack"],
  "fav.movie": "Deer Hunter",
  "friends": [
    {"age": 44, "first": "Dale", "last": "Murphy"},
    {"age": 68, "first": "Roger", "last": "Craig"},
    {"age": 47, "first": "Jane", "last": "Murphy"}
  ],
  "name": {"first": "Tom", "last": "Anderson"}
}

The full list of @pretty options are sortKeys, indent, prefix, and width. Please see Pretty Options for more information.

Custom modifiers

You can also add custom modifiers.

For example, here we create a modifier that makes the entire json document upper or lower case.

gjson.AddModifier("case", func(json, arg string) string {
  if arg == "upper" {
    return strings.ToUpper(json)
  }
  if arg == "lower" {
    return strings.ToLower(json)
  }
  return json
})
"children|@case:upper"           >> ["SARA","ALEX","JACK"]
"children|@case:lower|@reverse"  >> ["jack","alex","sara"]

JSON Lines

There's support for JSON Lines using the .. prefix, which treats a multilined document as an array.

For example:

{"name": "Gilbert", "age": 61}
{"name": "Alexa", "age": 34}
{"name": "May", "age": 57}
{"name": "Deloise", "age": 44}
..#                   >> 4
..1                   >> {"name": "Alexa", "age": 34}
..3                   >> {"name": "Deloise", "age": 44}
..#.name              >> ["Gilbert","Alexa","May","Deloise"]
..#(name="May").age   >> 57

The ForEachLines function will iterate through JSON lines.

gjson.ForEachLine(json, func(line gjson.Result) bool{
    println(line.String())
    return true
})

Get nested array values

Suppose you want all the last names from the following json:

{
  "programmers": [
    {
      "firstName": "Janet", 
      "lastName": "McLaughlin", 
    }, {
      "firstName": "Elliotte", 
      "lastName": "Hunter", 
    }, {
      "firstName": "Jason", 
      "lastName": "Harold", 
    }
  ]
}

You would use the path "programmers.#.lastName" like such:

result := gjson.Get(json, "programmers.#.lastName")
for _, name := range result.Array() {
	println(name.String())
}

You can also query an object inside an array:

name := gjson.Get(json, `programmers.#(lastName="Hunter").firstName`)
println(name.String())  // prints "Elliotte"

Iterate through an object or array

The ForEach function allows for quickly iterating through an object or array. The key and value are passed to the iterator function for objects. Only the value is passed for arrays. Returning false from an iterator will stop iteration.

result := gjson.Get(json, "programmers")
result.ForEach(func(key, value gjson.Result) bool {
	println(value.String()) 
	return true // keep iterating
})

Simple Parse and Get

There's a Parse(json) function that will do a simple parse, and result.Get(path) that will search a result.

For example, all of these will return the same result:

gjson.Parse(json).Get("name").Get("last")
gjson.Get(json, "name").Get("last")
gjson.Get(json, "name.last")

Check for the existence of a value

Sometimes you just want to know if a value exists.

value := gjson.Get(json, "name.last")
if !value.Exists() {
	println("no last name")
} else {
	println(value.String())
}

// Or as one step
if gjson.Get(json, "name.last").Exists() {
	println("has a last name")
}

Validate JSON

The Get* and Parse* functions expects that the json is well-formed. Bad json will not panic, but it may return back unexpected results.

If you are consuming JSON from an unpredictable source then you may want to validate prior to using GJSON.

if !gjson.Valid(json) {
	return errors.New("invalid json")
}
value := gjson.Get(json, "name.last")

Unmarshal to a map

To unmarshal to a map[string]interface{}:

m, ok := gjson.Parse(json).Value().(map[string]interface{})
if !ok {
	// not a map
}

Working with Bytes

If your JSON is contained in a []byte slice, there's the GetBytes function. This is preferred over Get(string(data), path).

var json []byte = ...
result := gjson.GetBytes(json, path)

If you are using the gjson.GetBytes(json, path) function and you want to avoid converting result.Raw to a []byte, then you can use this pattern:

var json []byte = ...
result := gjson.GetBytes(json, path)
var raw []byte
if result.Index > 0 {
    raw = json[result.Index:result.Index+len(result.Raw)]
} else {
    raw = []byte(result.Raw)
}

This is a best-effort no allocation sub slice of the original json. This method utilizes the result.Index field, which is the position of the raw data in the original json. It's possible that the value of result.Index equals zero, in which case the result.Raw is converted to a []byte.

Performance

Benchmarks of GJSON alongside encoding/json, ffjson, EasyJSON, jsonparser, and json-iterator

BenchmarkGJSONGet-16                11644512       311 ns/op       0 B/op	       0 allocs/op
BenchmarkGJSONUnmarshalMap-16        1122678      3094 ns/op    1920 B/op	      26 allocs/op
BenchmarkJSONUnmarshalMap-16          516681      6810 ns/op    2944 B/op	      69 allocs/op
BenchmarkJSONUnmarshalStruct-16       697053      5400 ns/op     928 B/op	      13 allocs/op
BenchmarkJSONDecoder-16               330450     10217 ns/op    3845 B/op	     160 allocs/op
BenchmarkFFJSONLexer-16              1424979      2585 ns/op     880 B/op	       8 allocs/op
BenchmarkEasyJSONLexer-16            3000000       729 ns/op     501 B/op	       5 allocs/op
BenchmarkJSONParserGet-16            3000000       366 ns/op      21 B/op	       0 allocs/op
BenchmarkJSONIterator-16             3000000       869 ns/op     693 B/op	      14 allocs/op

JSON document used:

{
  "widget": {
    "debug": "on",
    "window": {
      "title": "Sample Konfabulator Widget",
      "name": "main_window",
      "width": 500,
      "height": 500
    },
    "image": { 
      "src": "Images/Sun.png",
      "hOffset": 250,
      "vOffset": 250,
      "alignment": "center"
    },
    "text": {
      "data": "Click Here",
      "size": 36,
      "style": "bold",
      "vOffset": 100,
      "alignment": "center",
      "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
  }
}    

Each operation was rotated through one of the following search paths:

widget.window.name
widget.image.hOffset
widget.text.onMouseUp

These benchmarks were run on a MacBook Pro 16" 2.4 GHz Intel Core i9 using Go 1.17 and can be found here.

gjson's People

Contributors

ader1990 avatar aeneasr avatar baxiry avatar bcho avatar deefdragon avatar erikjohnston avatar harshavardhana avatar hexilee avatar ifraixedes avatar jalitha avatar janisz avatar kashav avatar kennygrant avatar l2nce avatar radarhere avatar realzhili avatar rkilingr avatar rustfix avatar speier avatar sspaink avatar svher avatar tidwall avatar v02460 avatar wi2l avatar zepatrik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gjson's Issues

Tag version

Release a version with Semantic versioning, please.

Map() triggers runtime "index out of range" error

This code:

https://github.com/whosonfirst/go-whosonfirst-geojson-v2/blob/master/properties/whosonfirst/whosonfirst.go#L299-L309

Is invoking this code:

https://github.com/tidwall/gjson/blob/master/gjson.go#L270-L277

When processing this file:

https://raw.githubusercontent.com/whosonfirst-data/whosonfirst-data/master/data/101/958/375/101958375.geojson

Resulting in this:

2017/08/30 16:34:26 get names for 101958375
panic: runtime error: index out of range

goroutine 13 [running]:
github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson.unescape(0xc459cbca2e, 0x17, 0x615210, 0x0)
	/usr/local/mapzen/go-whosonfirst-names-tools/src/github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson/gjson.go:1451 +0x6f3
github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson.tostr(0xc459cbca2d, 0x576, 0xc459cbca25, 0x7, 0xc459cbca26, 0x5)
	/usr/local/mapzen/go-whosonfirst-names-tools/src/github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson/gjson.go:559 +0xfc
github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson.Result.arrayOrMap(0x5, 0xc459cbc400, 0xba3, 0x0, 0x0, 0x0, 0x3a, 0x7b, 0x0, 0x0, ...)
	/usr/local/mapzen/go-whosonfirst-names-tools/src/github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson/gjson.go:365 +0x714
github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson.Result.Map(0x5, 0xc459cbc400, 0xba3, 0x0, 0x0, 0x0, 0x3a, 0xba3)
	/usr/local/mapzen/go-whosonfirst-names-tools/src/github.com/whosonfirst/go-whosonfirst-geojson-v2/vendor/github.com/tidwall/gjson/gjson.go:275 +0xbd
github.com/whosonfirst/go-whosonfirst-geojson-v2/properties/whosonfirst.Names(0x604240, 0xc420199cb0, 0x604240)

I think I am doing everything to test/handle return values correctly but maybe I am missing something?

How to get the nested array value?

if the json format is as the following:

v:=`
   {
    "programmers": [
        {
            "firstName": "Brett", 
            "lastName": "McLaughlin", 
            "email": "aaaa"
        }, 
        {
            "firstName": "Jason", 
            "lastName": "Hunter", 
            "email": "bbbb"
        }, 
        {
            "firstName": "Elliotte", 
            "lastName": "Harold", 
            "email": "cccc"
        }
    ]
}`

How the get the all values of the programmers.firstname?

How to differentiate between Object and Array?

After playing around with the library I tried to write a simple recursive JSON document visualizer, in order to do this I wanted to rely on the return values of gjson.Result.Type() but there is no differentiation for Object or Array there, only JSON.

The question is, how can I determine if a Result is an Array or an Object? Just calling Array() or Map() and checking the result does not seem to be the right way.

I may be missing something fundamental as well. Any pointers in the right direction will be greatly appreciated.

Mysterious missing result!

package main

import (
	"fmt"

	"github.com/tidwall/gjson"
)

func main() {

	json := `{"MarketName":null,"Nounce":6115}`
	r1 := gjson.GetMany(json, "Nounce", "Buys", "Sells", "Fills")
	fmt.Println(r1)
	r2 := gjson.GetMany(json, "Nounce", "Buys", "Sells")
	fmt.Println(r2)
	r3 := gjson.GetMany(json, "Nounce")
	fmt.Println(r3)
}
[   ]
[6115  ]
[6115]

This is a slightly bizarre bug, but I'd expect r1 to be equal to [6115 ]. Can't work out if it is related to the null in MarketName or the number of non-existent keys... Very mysterious :-)

Marshal json into map?

package main

import (
	"fmt"
	"encoding/json"
	"github.com/tidwall/gjson"
)
type A []struct {
	Id int64 `json:"id"`
	M map[string]int64 `json:"m"`
}
func main() {
	m:=map[string]int64{"a":1,"b":2}
	a := A{{Id:12,M:m}}
	bytes , _ := json.Marshal(a)
	
	b := A{}
	gjson.Unmarshal(bytes, &b)
	
  	fmt.Printf("%s\n %+v\n",bytes, b)
       // output: [{"id":12,"m":{"a":1,"b":2}}]
                       //  [{Id:12 M:map[]}]
       // nothing in map "M"
}

this not work;but it can work in "encoding/json"

some suggestions

  • change result.Int() returns int
  • add result.Int64() returns int64
  • change result.Uint() returns uint
  • add result.Uint64() returns uint64

Parse Errors Being Ignored

GetMany Result Incorrect

Thanks for the fast library. Have found that if I have the following JSON to process:
{"bar": {"id": 99, "mybar": "my mybar" }, "foo": {"myfoo": [605]}}

And my expressions are:
"foo.myfoo", "bar.id", "bar.mybar", "bar.mybarx"

Then the GetMany result returns the following:
[605] (correct!)
99 (correct!)
my mybar (correct!)
my mybar (incorrect!)

In this case the result for expression "bar.mybarx" should be blank as my JSON has no node "bar.mybarx"

Need help phrasing some json

I have some json from Konachan ( )
I would like to get the values for the key1,key2,key3 or key 4 but i can only figure how to get the values for the first key like:

apiurl := " https://konachan.net/post.json?limit=4&tags=foxgirl" res, err := http.Get(apiurl) if err != nil { fmt.Println(err.Error()) } defer res.Body.Close() thing, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err.Error()) } cut1 := bytes.TrimPrefix(thing , []byte("[")) cut2 := bytes.TrimSuffix(cut1 , []byte("]")) ans := gjson.ParseBytes(cut2) id := ans.Get("*id") fmt.Println(id)

My idea was geting the value of id in x key stored in a variable

Behavior of Array() on non-array field

Hi

I have a particular case where a field can be either an array of strings, or a string.
Naively I tried to use Array() on the result when the field is a simple string to see if it would return an array with a single element, but instead the returned array is empty.

So I tried another solution, using the myfield.# notation on a non-array field, and I expected it to be zero, but instead i get null.

Do you know how I should address this use-case ? Would it be possible to return an array with a single element when using Array() on a non-array field ?

William

Parsing of large integer ids is broken: integers should remain integers

Hi,

Thanks for making this great library available!

There is a flaw when parsing large integer ids. It's common in REST APIs to use large integer ids for entity ids - often they encode time info in them, and they have nothing to do with an RDB autoincrement sequence.

In this case, gsjon is parsing those JSON integers into float64, and the precision of the id is being lost, rendering it useless. JSON integers should be parsed into int64 not float64. I know that the default go json package also parses all numbers into float64, but that also feels wrong to me. JSON says nothing about numerical types only that they could be integers or floats, and JSON parsing in most other languages like Ruby, Objective-C, etc., will choose the correct numerical type in the language based on the observed type of the literal (e.g. 6.2 would be a float but 6 would be an integer) and the type of the field's values can vary from one record to another: the same field could be a float from a literal of 6.2 but an integer from a float of 6.

Here's an example in go using gjson:

jsonString := `{"IdentityData":{"GameInstanceId":634866135153775564}}`
value := gjson.Get(jsonString, "IdentityData.GameInstanceId")

// gjson has stored value as float64 and any use of it seems to produce
// 634866135153775616.0, which is the wrong id and
// even gjson.GetBytes([]byte(jsonString), "IdentityData.GameInstanceId")) prints as
// a float64 634866135153775616.0

// This seems to be the only way to get the correct id
gameInstanceIdString := gjson.Get(jsonString, "IdentityData.GameInstanceId").Raw
gameInstanceId, errGameInstanceId := strconv.ParseInt(gameInstanceIdString, 10, 64)
if errGameInstanceId != nil {
  // We can use gameInstanceId and it will be the correct value of 634866135153775564
}

That is pretty cumbersome just to get an integer id out of some json. I love gjson - it's well-designed and a breeze to use, but having to do all this just to preserve the true value of an integer id makes gjson a lot less compelling.

Am I missing something here? Is there an easier way to do this?

If this was some kind of large measurement or something, I guess the imprecision/rounding wouldn't be as big a deal. But this is an id, and 634866135153775616 is not useful when we really need the true value 634866135153775564.

Any help would be hugely appreciated!

How can I get the root arrays with gjson?

The body content is

[
{
    "client_id": 1000,
    "edge_ip": "xx.xx.xx.xx",
    "edge_port": port1,
    "timestamp":123456
},
{
    "client_id": 1001,
    "edge_ip": "yy.yy.yy.yy",
    "edge_port": port2,
    "timestamp":123456
}
]

How can I get all the objects through like this: gjson.Get(body, "*").Array()?

Defaults for Nil Case

Hey all - absolutely love this library. We use it extensively in our server platform. We do a ton of nil catching, since our marshaller converts then to "null". I was wondering if there had been any thought to allowing a default value that could be used if a value isn't found.

Errors are not using. Yes, it is a big problem.

I don't understand, why are you hating errors? It is normal to return error that "sorry, i can't find this object in your json" when you call gjson.Get() or "sorry, i can't translate array to string, Cause... Cause it's an array" for result.String(). It is pretty easy, but you didn't made it, why?

Do not support large numbers

package main

import (
	"fmt"
	"github.com/tidwall/gjson"
	"time"
)

func main() {
	var json_str = fmt.Sprintf(`{"id":%d}`, time.Now().UnixNano())
	fmt.Println(json_str)
	fmt.Println(gjson.Get(json_str, "id"))

}

Feature request: new method Position() on gjson.Result object

Hi,

somehow related to tidwall/sjson#8.

it would be nice to have a method on the returning result object for getting the position where the object was found in the array if one uses:

field := gjson.GetBytes(jsonstring, `user.#[name="tidwall"]`)

and if jsonstring was an array of objects:

{
  "user": [
     {"id": ..., "name": "tidwall"},
     {"id": ..., "name": "omani"},
     {"id": ..., "name": "...."}
  ]
}

now I could get the position where the element was found with Pos() or Position():

fmt.Println(field.Pos())
// Output
0

are there any plans to implement this?

Select all matches in array

Go playground: https://play.golang.org/p/hDZZPbCwXD

For this JSON:

{
  "friends": [
    {
      "first": "James",
      "last": "Murphy"
    },
    {
      "first": "Roger",
      "last": "Craig"
    },
    {
      "first": "James",
      "last": "The Second"
    }
  ]
}
allJames := gjson.Get(jsonData, `friends.#[first="James"]`)

gives me just {"first": "James", "last": "Murphy"}

How would one select both "James" friends?

check the delimiter correctly

Hi, tidwall:

I use the wrong JSON delimiter, and I can also get results without errors.

var gpsSample = `
{
    "id"&& "950446", 
    "lat": 23.1483333, 
    "lon": 113.2547222, 
    "height": 0, 
    "dir": 42.5, 
    "speed": 30, 
    "attr": "routecode::00540", 
    "group": "591a8e25d1779c525b732105", 
    "gpstime": "2017-05-23T11:31:24+08:00"
}
`

func TestGjson(t *testing.T) {
	require.Equal(t, "950446", gjson.Get(gpsSample, "id").String())
}

image

Escape Sequence Not Working?

Hey, there.

I'm trying to access data in a JSON file with a map that has "." in its keys, and the escape character "" isn't working. It might have something to do with the fact that I'm working on Linux (which has different path endings compared to Windows). Here's the JSON file I'm working with. Nothing I do allows me to access "frames.Player 0.ase" - even gjson.Get(file, "frames.#").

use of the unsafe package

GJSON makes use of the standard Go unsafe package for the GetBytes() and GetBytesMany() functions. It carefully uses unsafe to help avoid one extra memory allocation and provides an itty-bitty performance boost.

It's totally safe to use this package, but in case your project or organization restricts the use of unsafe, there's the gjson-safe package.

The result is a problem: query Matches

json

{
"data":[{
  "uid": 1,
}, {
  "uid": 2,
}]
}

path: gjson.Get(json, `data.#[uid!=1]`).Raw

result: "uid": 1,

why?

gjson.go line 1079 is error

case "!=":
    return value.Num == rpvn

should be:

case "!=":
    return value.Num != rpvn

Unable to access the index of array when apply ForEach func

I have read the code and comment on func ForEach,
you didn't pass the index to arguments on purpose,
thus, if I want to get the index of each item, i need to do like this

var p = res.Array()
for i := 0; i < len(p); i++ {
}

And I also program with javascript, you know, javascript has the prototype foreach too.
refs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
So, when the first time I see this function, I may think the key will be the index of items in array.
what's your recommend for getting index about this?

Query many paths at once

@tidwall hello, thanks for a nice library.

I have a question - in my case I need to query several keys from JSON payload, all on top level. As far as I understand it's only possible to do in several calls to Get method. It could be much more efficient to have something like GetMany which accepts a list of paths and returns several Result objects making only one scan over JSON payload. Something like EachKey method from jsonparser lib.

I looked into gjson internals and it seems to me that it's not an easy task to add such a feature. But I just decided to ask - what do you think about this?

If one key is having other key value as a prefix, getManyBytes function is returning wrong values

Sample test case :

package main_test

import (
"testing"
"github.com/tidwall/gjson"
"github.com/stretchr/testify/assert"
)

func Test_GJson(t *testing.T) {
result := gjson.GetManyBytes([]byte(sampleJSON), "name", "name1", "address", "addressDetails")
expectedValues := []string{"FirstName", "FirstName1", "address1", "address2"}
assert.Equal(t, expectedValues[0], result[0].String())
assert.Equal(t, expectedValues[1], result[1].String())
assert.Equal(t, expectedValues[2], result[2].String())
assert.Equal(t, expectedValues[3], result[3].String())
}

const sampleJSON = { "name": "FirstName", "name1": "FirstName1", "address": "address1", "addressDetails": "address2", }


Explanation : This test case is failing. It gives "FirstName" as a value for both keys "name" and "name1". If one key is present as a prefix in other key, GetManyBytes function is returning wrong values.

Exists, IsObject, and IsArray fail on invalid JSON

j := gjson.Parse("{")
fmt.Printf("Exists: %v IsObject: %v\n", j.Exists(), j.IsObject())

Results in:

Exists: true IsObject: true

Additionally:

j := gjson.Parse("[")
fmt.Printf("Exists: %v IsArray: %v\n", j.Exists(), j.IsArray())

Results in:

Exists: true IsArray: true

I would expect that .Exists() would return false.

GetMany Result Value Missing

Have found that if I have the following JSON to process:
{"bar": {"id": 99, "xyz": "my xyz"}, "foo": {"myfoo": [605]}}

And my expressions are:
"foo.myfoo", "bar.id", "bar.xyz", "bar.abc"

Then the GetMany result returns the following:
(blank - incorrect!)
99 (correct!)
my xyz (correct!)
(blank - correct!)

In this case the result for expression "foo.myfoo" should be the array [605] however the result is empty for this expression.

Regression defect introduced by fix of https://github.com/tidwall/gjson/issues/20

commit id of fix - 256887a
This fix has introduced regression defect.

Current sample failing test case:

package main_test

import (
"testing"
"github.com/tidwall/gjson"
"github.com/stretchr/testify/assert"
"fmt"
)

func Test_GJson(t *testing.T) {
result := gjson.GetManyBytes([]byte(sampleJSON), "Level1Field1", "Level1Field2.Level2Field1", "Level1Field2.Level2Field2.Level3Field1", "Level1Field4")
assert.Equal(t, "3", result[0].String())
assert.Equal(t, expectedValue1, result[1].String())
assert.Equal(t, expectedValue2, result[2].String())
assert.Equal(t, "4", result[3].String())
}

const expectedValue1 = [ "value1", "value2" ]

const expectedValue2 = [ { "key1":"value1" } ]

const sampleJSON = { "Level1Field1":3, "Level1Field4":4, "Level1Field2":{ "Level2Field1":[ "value1", "value2" ], "Level2Field2":{ "Level3Field1":[ { "key1":"value1" } ] } } }

Getting the key from a result

Is it possible to get the key from a result?

{
    "values": [
        { "name": "Jack" },
        { "name": "Paul" }
    ]
}
value := gjson.Get(json, "values.#.name")

for _, result := range value.Array() {
	fmt.Printf("%s", ...) // Can I get the actual key here? i.e. values.0.name, values.1.name, etc...
}

Select array element as a whole

See playground snippet here: https://play.golang.org/p/lnK6hp8ECs

From the following example JSON:

[
  {
    "items": [
      {
        "id": "id-a1",
        "cost": "cost-a1",
        "rating": "terrible"
      },
      {
        "id": "id-a2",
        "cost": "cost-a2",
        "rating": "bad"
      }
    ],
    "tag": "abc"
  },
  {
    "items": [
      {
        "id": "id-b1",
        "cost": "cost-b1",
        "rating": "bad"
      },
      {
        "id": "id-b2",
        "cost": "cost-b2",
        "rating": "good"
      }
    ],
    "tag": "xyz"
  }
]

I'd like to select from the array a collection of items and the tags that correspond to each item set array. For example, when selecting from the collection items with rating = good, I would get the following ideal outcome:

[
  [
    {
      "id": "id-b2",
      "cost": "cost-b2",
      "rating": "good"
    }
  ],
  [
    "xyz"
  ]
]
gjson.GetMany(jsonData, `#.items.#[rating="good"]`, `#.tag`)

gets me close, by just returning item id-b2, but still gives me both tags xyz and abc in the second array returned. Ideally that second array would give me just xyz .

Is this type of selection outcome even possible at the moment?

Also, I'm not sure if I've been able to explain the problem appropriately, but I thought it would be easier to explain via a (very) hypothetical JSON example that I distilled from a more complex real-world JSON setup.

Nested slice return error

fmt.Println(gjson.Get(jstr, "areas.2.points.#"))

output : 7 ? why?

jstr sample:

{
"areas":[
{
"name":"南站区域",
"type":"circle",
"lon":113.26342,
"lat":22.99095,
"radius":0.47
},
{
"name":"省市站区域",
"type":"circle",
"lon":113.24723,
"lat":23.15074,
"radius":0.21
},
{
"name":"火车站公交总站区域",
"type":"polygon",
"points":[
{
"lon":113.251895,
"lat":23.150811
},
{
"lon":113.254116,
"lat":23.150811
},
{
"lon":113.254116,
"lat":23.148808
},
{
"lon":113.251895,
"lat":23.148808
}
]
}
]
}

Parse an array

How to parse an array?

[
"string",
{
"object":{},
"array":[],
}
]

Google App Engine Support

Hi!

I would really like to use this package for a project using Google App Engine, but I get this error:

go-app-builder: Failed parsing input: parser: bad import "unsafe" in github.com/tidwall/gjson/gjson.go from GOPATH

I was hoping there might be an simple way to replace unsafe.Pointer so that it will work on App Engine?

Thanks a lot!

Validating JSON

The documentation tells us that

This function expects that the json is well-formed. Bad json will not panic, but it may return back unexpected results. When the value is found it's returned immediately.

And I'm asking myself if there is any reason not to use encoding/json in a separated optional method in order to make this check, normally after using gjson.Parse(...).

Result could be the receiver for this method/function. I can think of two possibilities.

  1. Just return a bool and do not explain what is wrong.
func (t Result) IsValidJson() bool {
	var jsonTester interface{}
	err := json.Unmarshal([]byte(t.Raw), &jsonTester)
	return err == nil
}
  1. return an error explaining what is wrong, and the user must check against == nil for checking that the JSON is valid.
func (t Result) ValidateJson() error{
	var jsonTester interface{}
	return json.Unmarshal([]byte(t.Raw), &jsonTester)
}

Right now I'm doing this using additional helper methods in my project.

Strange behaviour in GetMany

Hi!
Flowing code:

json := `{"one": {"two": 2, "three": 3}, "four": 4, "five": 5}`
results := gjson.GetMany(json, "four", "five", "one.two", "one.six")
for i,r := range  results {
	fmt.Printf("%d: %v\n", i, r)
}

produces:

0:
1:
2: 2
3:

Is it correct?
Thank You!

Passes fuzzing

No issue here, just wanted to let you know, I threw go-fuzz at gjson for a couple days with ~2 billion runs, no locks or panics found. Nice job! 👍

How do you get the value of multi- array

data := `{
  "code": 0,
  "msg": "",
  "data": {
    "sz002024": {
      "qfqday": [
        [
          "2014-01-02",
          "8.93",
          "9.03",
          "9.17",
          "8.88",
          "621143.00"
        ],
        [
          "2014-01-03",
          "9.03",
          "9.30",
          "9.47",
          "8.98",
          "1624438.00"
        ]
      ]
    }
  }
}`

How to get?

var num []string
num = ["2014-01-02","8.93","9.03","9.17","8.88","621143.00"]

Possible gjson parsing bug?

Hi,

Wanted to say firstly thanks for all the hard work on gjson. I love this library. Unfortunately, I might've found another bug to report? I just tested this against the latest release.

Please see this repo: https://github.com/rbastic2/gjson-bug

Running go test -v should cause the test to fail. The data used is in rules_test.go (see the getHookRules() function) and the problematic path is in the error:

HOOKFUNCTIONS.SetUpdate.#0.is_true

I have a workaround for this bug in the meantime, by not retrieving the entire path on every instance (wasteful, anyway). However, I thought it would present a good opportunity to further fuzz gjson for you. Hope I'm not doing something wrong with the path syntax :D

Thanks in advance!

Unicode emoji not decoded properly

With the code below, the first line will show bad decoded chars, while the second one, with standard unmarshal function is OK.

package main

import (
	"encoding/json"

	"github.com/tidwall/gjson"
)

const input = `{"utf8":"Example emoji, KO: \ud83d\udd13, \ud83c\udfc3 OK: \u2764\ufe0f "}`

func main() {
	value := gjson.Get(input, "utf8")
	println(value.String())

	var s string
	json.Unmarshal([]byte(value.Raw), &s)
	println(s)
}

ForEach() and "Result"

I am new to golang, and am following the example in ReadMe and trying iterate / traverse a nested json, but got an error "undefined: Result". Is the following example in ReadMe a "meta" code? If so, could you give a more concrete executable example to help?

result := gjson.Get(json, "programmers")
result.ForEach(func(key, value Result) bool{
    println(value.String()) 
    return true // keep iterating
})

if I change Result to any declared variable a, the error becomes a is not a type...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.