PaesslerAG / jsonpath

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

No error with incorrect path and missing field #25

Open Ezri-Mudde opened 4 years ago

Ezri-Mudde commented 4 years ago

When path doesn't begin with a $ Get doesn't return an error when the field doesn't exist, Get does return an error when path begins with $. See example below or use playground

package main

import (
    "encoding/json"
    "fmt"
    "github.com/PaesslerAG/jsonpath"
)

func main() {
    v := interface{}(nil)
    json.Unmarshal([]byte(`{
    "welcome":{
            "123456":["Good Morning", "Hello World!"]
        }
    }`), &v)

    if unknownWithoutPrefix, err := jsonpath.Get("nope", v); err != nil {
        fmt.Printf("Error: %s\n", err)
    } else if unknownWithoutPrefix == nil {
        fmt.Println("no value for missing field and no error")
    }

    if knownWithoutPrefix, err := jsonpath.Get("welcome", v); err == nil {
        fmt.Printf("welcome: %v\n", knownWithoutPrefix)
    }

    if unknownWithPrefix, err := jsonpath.Get("$.nope", v); err != nil {
        fmt.Printf("Error: %s\n", err)
    } else {
        fmt.Println(unknownWithPrefix)
    }
}