From df0b0cce42ab76cc06c7d22e5b5937a47a6b2bee Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Sun, 18 Feb 2018 09:49:01 -0700 Subject: [PATCH] section on json validation --- README.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6af67e5..70240d9 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,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. Bad 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". When the value is found it's returned immediately. ```go package main @@ -275,6 +275,19 @@ if gjson.Get(json, "name.last").Exists() { } ``` +## 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. + +```go +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{}`: