PaesslerAG / jsonpath

BSD 3-Clause "New" or "Revised" License
172 stars 37 forks source link

Support for `json.Number` #35

Open mihaitodor opened 1 year ago

mihaitodor commented 1 year ago

First of all, thank you for for this library!

Would you consider adding support for json.Number? More specifically, json.Decoder has the UseNumber() method which can be used to decode number values to json.Number instead of float64. Here is some sample code:

package main

import (
    "context"
    "encoding/json"
    "strings"

    "github.com/PaesslerAG/gval"
    "github.com/PaesslerAG/jsonpath"
    "github.com/generikvault/gvalstrings"
)

func main() {
    jsonPathLanguage := gval.Full(jsonpath.Language(), gvalstrings.SingleQuoted())

    eval, err := jsonPathLanguage.NewEvaluable(`$.body[?(@.type==1)]`)
    if err != nil {
        panic(err)
    }

    parsed := map[string]any{}
    d := json.NewDecoder(strings.NewReader(`{"body":[{"type":1,"id":"foo"},{"type":2,"id":"bar"}]}`))
    d.UseNumber()
    if err := d.Decode(&parsed); err != nil {
        panic(err)
    }

    x, err := eval(context.Background(), parsed)
    if err != nil {
        panic(err)
    }

    v, err := json.Marshal(x)
    if err != nil {
        panic(err)
    }

    println(string(v))
}

If you comment out d.UseNumber(), then the output will be [{"id":"foo","type":1}] instead of [].

Note: If I change $.body[?(@.type==1)] to $.body[?(@.type>1)], then the query does return [{"id":"bar","type":2}] when using d.UseNumber().

I haven't looked at the code in detail yet, but I can try to dig into it if you'd be interested in a PR.