From 2e78916f4a673a1fad21b66aa8e2490f9a691dd2 Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Mon, 8 May 2017 17:47:46 -0700 Subject: [PATCH] option to disable validation --- README.md | 2 +- gjson.go | 21 ++++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e8c6c82..9c009cd 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ $ 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". 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 package main diff --git a/gjson.go b/gjson.go index 8e9afcb..cc83364 100644 --- a/gjson.go +++ b/gjson.go @@ -9,6 +9,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "unicode/utf16" "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. // // 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 // assigned to Go string, int, byte, uint64, etc. This rule applies to all types. func Unmarshal(data []byte, v interface{}) error { - _, ok := validpayload(data, 0) - if !ok { - return errors.New("invalid json") + if atomic.LoadUintptr(&validate) == 1 { + _, ok := validpayload(data, 0) + if !ok { + return errors.New("invalid json") + } } if v := reflect.ValueOf(v); v.Kind() == reflect.Ptr { assign(ParseBytes(data), v)