Working with JSON
This section contains all json related manipulations, using helper functions, gjson.Result object and modifier functions that could be used during path assembly for the gjson.Result.Get calls.
Name | Description | Usage | Samples |
---|---|---|---|
toJson | Attempts to convert a type to valid json. Can be used on list types or entities to get the structure for JS usage. | toJson(data) string | {{ toJson .Data.WMSApi.InboundEfficiencyList }} |
jsonLookup | Looking json value by path. May return different types: int, string, etc… If under path json, returns map[string]any | jsonLookup(jsonStr, path) any | {{ jsonLookup `{“foo”:“bar”}` “foo” }} |
jsonLookupRaw | Looking json value by path. Always returns string. If under path json, returns stringified json | JsonLookupRaw(jsonStr, path) string | {{ JsonLookupRaw `{“foo”:“bar”}` “foo” }} |
jsonType | Returns json type for path. Values: “Null”, “Number”, “String”, “JSON”, “Boolean” | JsonType(jsonStr, path) string | {{ JsonType `{“foo”:“bar”}` “foo” }} |
jsonArrayLen | Returns length of json array. Returns 0 if under path is object | JsonArrayLen(jsonStr, path) int | {{ JsonArrayLen [] "" }} |
jsonObjKeys | Returns all keys of json object under path. | JsonObjKeys(jsonStr, path) int | {{ JsonObjKeys `{“foo”:1,“bar”:2}` "" }} |
jsonResult | Returns JSON Result object containing many valuable functions and fields. More details | jsonResult(jsonStr, path) gjson.Result | {{ jsonResult `{“foo”:1,“bar”:2}` “foo” }} |
jsonPretty | Takes in string or []byte and returns beautified json |
jsonPretty(json) string | {{ jsonPretty `{“foo”:1,“bar”:2}` }} |
jsonSet | Adds values to and existing json structure | jsonSet(json, path, val) string | {{ jsonSet `{“foo”: 1}` “bar” 2 }} |
jsonSetObj | Adds an entire raw json string object or array structure | jsonSetObj(json, path, val) string | {{ jsonSetObj `{“foo”: 1}` “bar” `{“someObject”: “test”}` }} |
jsonDel | Remove values from an existing json structure | jsonDel(json, path) string | {{ jsonDel `{“foo”: 1, “bar: 2}` “bar” }} |
Samples
JSON sample payload
{
"name": {
"first": "Tom",
"last": "Anderson"
},
"age": 37,
"children": [
"Sara",
"Alex",
"Jack"
],
"emptyArray": [],
"fav.movie": "Deer Hunter",
"friends": [
{
"first": "Dale",
"last": "Murphy",
"age": 44,
"nets": [
"ig",
"fb",
"tw"
]
},
{
"first": "Roger",
"last": "Craig",
"age": 68,
"nets": [
"fb",
"tw"
]
},
{
"first": "Jane",
"last": "Murphy",
"age": 47,
"nets": [
"ig",
"tw"
]
}
]
}
Function usage examples
<div>
{{ $jsonStr := `{"name": {"first": "Tom", "last": "Anderson"},"age":37,"children":
["Sara","Alex","Jack"],"emptyArray": [],"fav.movie": "Deer Hunter","friends": [{"first": "Dale",
"last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]},{"first": "Roger", "last": "Craig",
"age": 68, "nets": ["fb", "tw"]},{"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig",
"tw"]}]}`}}
<p>Get value: <code>{{ jsonLookup $jsonStr "age" }}</code></p>
<!-- 37 -->
<p>Get value map: <code>{{ jsonLookup $jsonStr "name" }}</code></p>
<!-- map[first:Tom last:Anderson] -->
<p>Get value as string: <code>{{ jsonLookupRaw $jsonStr "age" }}</code></p> <
!-- "37" -->
<p>Get obj as string: <code>{{ jsonLookupRaw $jsonStr "name" }}</code></p>
<!-- {"first": "Tom", "last": "Anderson"} -->
<p>Get json type: <code>{{ jsonType $jsonStr "name" }}</code></p>
<!-- JSON -->
<p>Get json type: <code>{{ jsonType $jsonStr "age" }}</code></p>
<!-- Number -->
<p>Get json type: <code>{{ jsonType $jsonStr "children" }}</code></p>
<!-- JSON -->
<p>Get json type: <code>{{ jsonType $jsonStr "not_exist" }}</code></p>
<!-- NULL -->
<p>Json array length: <code>{{ jsonArrayLen $jsonStr "children" }}</code></p>
<!-- 3 -->
<p>Json array length (object): <code>{{ jsonArrayLen $jsonStr "name" }}</code></p>
<!-- 0 -->
<p>Json object keys root: <code>{{ jsonObjKeys $jsonStr "" }}</code></p>
<!-- [name age children emptyArray fav.movie friends] -->
<p>Json object keys path: <code>{{ jsonObjKeys $jsonStr "name" }}</code></p>
<!-- [first last] -->
<p>Json object keys array: <code>{{ jsonObjKeys $jsonStr "children" }}</code></p>
<!-- [] -->
</div>
JSON Result object
GOERP uses library gjson to read and process json at specific
path. Helper function jsonResult
returns gjson.Result
object which contains many valuable fields
and functions for json processing. All those functions and fields may significantly simplify work
with json inside templates.
Fields
Name | Description | Usage | Samples |
---|---|---|---|
Type | Type is the json type (Null, False, Number, String, True, JSON) | Result.Type.String() string | {{ $result.Type }} |
Raw | Raw is the raw json | Result.Raw string | {{ $result.Raw }} |
Index | Index of raw value in original json, zero means index unknown | Result.Index int | {{ $result.Index }} |
Indexes | Indexes of all the elements that match on a path containing the ‘#’ query character | Result.Indexes []int | {{ $result.Indexes }} |
Functions
Name | Description | Usage | Samples |
---|---|---|---|
String | Returns a string representation of the value | String() string | {{ $result.String }} |
Bool | Returns a boolean representation of the value | Bool() bool | {{ $result.Bool }} |
Int | Returns a integer representation of the value | Int() int64 | {{ $result.Int }} |
Uint | Returns a unsigned integer representation of the value | Uint() uint64 | {{ $result.Uint }} |
Float | Returns a float representation of the value | Float() float64 | {{ $result.Float }} |
Time | Returns a time.Time representation of the value | Time() time.Time | {{ $result.Time }} |
Array | Returns array of elements as Result objects | Array() []Result | {{ $result.Array }} |
IsObject | Returns true if result is a json object | IsObject() bool | {{ if $result.IsObject }} {{ end }} |
IsArray | Returns true if result is a json array | IsArray() bool | {{ if $result.IsArray }} {{ end }} |
IsBool | Returns true if result is a json boolean | IsBool() bool | {{ if $result.IsBool }} {{ end }} |
Map | Returns map of nested results. root Result must be json object | Map() map[string]Result | {{ $result.Map }} |
Get | Searches result for the specified path. Check queries guide for more info and playground | Get(path string) Result | {{ $result.Get $path }} |
Exists | Returns true if json value exists | Exists() bool | {{ if $result.Exists }} {{ end }} |
Value | Returns value of related type (int, string, etc.), map[string]any for json objects and []any for arrays | Value() any | {{ $result.Value }} |
Less | Return true if a token is less than another token. Null < False < Number < String < True < JSON | Less(token Result, caseSensitive bool) bool | {{ $result.Less $result2 false }} |
Paths | Paths returns the original GJSON paths for a Result | Paths(json string) []string | {{ $result.Paths $entireJson }} |
Path | Paths returns the original GJSON path for a Result | Path(json string) string | {{ $result.Path $entireJson }} |
Modifier functions
Modifier functions could be used in paths for the gjson.Result. They always starts with @
(e.g.
@sum
) and may be chained using |
(e.g. @sum:2|@suffix:$
). Also, some modifiers may accept
additional arguments that could be passed through :
(e.g. @sum:2
, which is decimals in this
case).
Please note, $r
in samples is the gjson.Result
object.
Name | Description | Usage | Samples |
---|---|---|---|
commaSepStr | Converts json array to comma separated string. null , {} s and [] s would be skipped. When working with numbers, pass int as an argument |
“@commaSepStr:arg” | {{ $r.Get “@commaSepStr” }} |
arrToStr | Same as commaSepStr, but allows to define the separator through arguments. | “@arrToStr:arg” | {{ $r.Get “@arrToStr:;” }} |
prefix | Sets prefix to the value | “@prefix:arg” | {{ $r.Get “@prefix:pref_” }} |
suffix | Sets suffix to the value | “@suffix:arg” | {{ $r.Get “@suffix:_suf” }} |
getOldestItemDate | Automation specific. Returns oldest record from items array. Arg: format of output date | “@getOldestItemDate:arg” | {{ $r.Get “@getOldestItemDate:2006-01-02T15:04:05Z” }} |
unique | Removes duplicates from the json array | “@unique” | {{ $r.Get “@unique” }} |
notNull | Removes null s from the json array |
“@notNull” | {{ $r.Get “@notNull” }} |
sum | Sums up all values in json array, stringified numbers are valid, other types are ignored. Define decimals through arg | “@sum:arg” | {{ $r.Get “@sum:2” }} |
min | Extracts minimum number from json array, same restrictions as in sum |
“@min” | {{ $r.Get “@min” }} |
max | Extracts maximum number from json array, same restrictions as in sum |
“@max” | {{ $r.Get “@max” }} |
skip | Allows to skip value (returns empty value) based on conditions: Supported args: zero , eq,val , neq,val , gt,val , lt,val |
“@skip:arg” | {{ $r.Get “@skip:eq,John” }} |