option to disable validation

This commit is contained in:
Josh Baker 2017-05-08 17:47:46 -07:00
parent 2555fc0b61
commit 2e78916f4a
2 changed files with 19 additions and 4 deletions

View File

@ -26,7 +26,7 @@ $ go get -u github.com/tidwall/gjson
This will retrieve the library. This will retrieve the library.
## Get a value ## Get a value
Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". This function expects that the json is well-formed and validates. Invalid json will not panic, but it may return back unexpected results. When the value is found it's returned immediately. Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". 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.
```go ```go
package main package main

View File

@ -9,6 +9,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"unicode/utf16" "unicode/utf16"
"unicode/utf8" "unicode/utf8"
@ -2059,6 +2060,18 @@ func assign(jsval Result, goval reflect.Value) {
} }
} }
var validate uintptr = 1
// UnmarshalValidationEnabled provides the option to disable JSON validation
// during the Unmarshal routine. Validation is enabled by default.
func UnmarshalValidationEnabled(enabled bool) {
if enabled {
atomic.StoreUintptr(&validate, 1)
} else {
atomic.StoreUintptr(&validate, 0)
}
}
// Unmarshal loads the JSON data into the value pointed to by v. // Unmarshal loads the JSON data into the value pointed to by v.
// //
// This function works almost identically to json.Unmarshal except that // This function works almost identically to json.Unmarshal except that
@ -2066,9 +2079,11 @@ func assign(jsval Result, goval reflect.Value) {
// type. For example, the JSON string "100" or the JSON number 100 can be equally // type. For example, the JSON string "100" or the JSON number 100 can be equally
// assigned to Go string, int, byte, uint64, etc. This rule applies to all types. // assigned to Go string, int, byte, uint64, etc. This rule applies to all types.
func Unmarshal(data []byte, v interface{}) error { func Unmarshal(data []byte, v interface{}) error {
_, ok := validpayload(data, 0) if atomic.LoadUintptr(&validate) == 1 {
if !ok { _, ok := validpayload(data, 0)
return errors.New("invalid json") if !ok {
return errors.New("invalid json")
}
} }
if v := reflect.ValueOf(v); v.Kind() == reflect.Ptr { if v := reflect.ValueOf(v); v.Kind() == reflect.Ptr {
assign(ParseBytes(data), v) assign(ParseBytes(data), v)