varToJSON Function
Syntax
Arguments
- varAny Type
Variable to convert to JSON
- flagSpecialTagsLogical
(optional) Set to .T. to use {...} tags; defaults to .F.
- flagCondenseLogical
(optional) Set to .T. to remove pretty formatting
- indentCharacter
(optional) Set to some number of spaces for indented formatting
- flagQuotesOnPropNamesLogical
(optional) Set to .T. to quote property names
- flagHonorNullsLogical
(optional)
Description
Converts an Xbasic variable to a JSON representation.
Discussion
The varToJSON() function converts an Xbasic variable to a JSON representation. If flagSpecialTags is .t. then you can use {function} and optional {functionArguments:var1,var2} in a property value to encode as a function. You can also use {Javascript} for arbitrary Javascript. With varToJSON vs varToJSONStandard the difference is that JSONStandard uses double quotes while varToJSON assumes single quotes. The varToJSONStandard() function is preferred.
See Also a5_JSON_Prep Function
Try this in an interactive session.
dim p as p p.name = "selwyn" p.onchange = "{function}alert('onchange')" p.onClick = "{function}alert('onclick')" ?p = name = "selwyn" onchange = "{function}alert('onchange')" onClick = "{function}alert('onclick')" x = varToJSON(p,.f.) ?x = { name: 'selwyn', onchange: '{function}alert(\'onchange\')', onClick: '{function}alert(\'onclick\')' } y = varToJSON(p,.t.) ?y = { name: 'selwyn', onchange: function() {alert('onchange')}, onClick: function() {alert('onclick')} }
In the script example below
1. We use {functionarguments:arg1,arg2,arg3} to specify arguments for a functions
2. We demonstrate how Xbasic property arrays translate to js arrays of object literals
3. We demonstrate how the helper function a5_json_prep() removes properties with blank values (e.g. p.city).
dim p as p dim p.children[0] as p p.name = "selwyn" p.surname = "{function}alert('onchange')" i = p.children.append() p.children[i].name = "{function}alert('onclick')" p.children[i].age = 4 i = p.children.append() p.children[i].name = "Joe" p.children[i].age = 6 p.city = "Smith" p.myfunc = "Emma"+"Zoe" a5_JSON_Prep(p) showvar(varToJSON(p,.t.))
This will display:
{ children: [ { name: function() {alert('onclick')}, age: 4 }, { name: 'Joe', age: 6 } ], name: 'selwyn', surname: function() {alert('onchange')}, city: 'Smith', myfunc: 'EmmaZoe' }
See Also