Extension::JsonForEachString Method
Syntax
Arguments
- jsonCharacter
A JSON string.
- expressionCharacter
An Xbasic expression used to format the value of fields in the JSON string.
- fieldsCharacter
Default = "" (all fields). A comma delimited list of fields to process. If not specified, all fields are processed.
Returns
- reformatted_jsonCharacter
Returns the processed JSON.
Description
For each string in json, evaluate the expression to 'replace' the string.
Discussion
The ForEachString() method can be used to process every string in a JSON object using an expression. The expression can be used to replace values in the JSON.
This method is similar to the Xbasic *for_each() function, except that it is designed to operate on property values in a JSON string.
For example:
dim json as c = <<%str% { "name" : "name Smith " , "alias" : [ "jj " , "name " ] , "id" : { "name" : "name_01 " } } %str%
Notice that the string 'name' appears in the above JSON as both a property name and also in a property value.
We want to change 'name' to 'John', without changing the names of any of the property values. Also, note that each property value has trailing spaces.
' change 'name' to 'John' json = extension::json::ForEachString(json,"strtran(value,'name','John')") 'trim trailing spaces from each property value json = extension::json::ForEachString(json,"trim(value)")
Result:
{ "name" : "John Smith" , "alias" : [ "jj" , "John" ] , "id" : { "name" : "John_01" } }
Notice that none of the property names were changed.
To restrict what properties are changed, a comma delimited list of field names can be passed in as the third argument to the ForEachString() method. For example, in the script below, only the 'name' fields are updated:
' only process fields called 'name': ? extension::JSON::ForEachString(json, "strtran(value,'name','John')","name") = { "name" : "John Smith " , "alias" : [ "jj " , "name " ] , "id" : { "name" : "John_01 " } }