varToJSON Function

This method is deprecated. Use json_generate() instead.


C Result = varToJSON(* var [,L flagSpecialTags [,L flagCondense [,C indent [,L flagQuotesOnPropNames [,L flagHonorNulls ]]]]])


varAny Type

Variable to convert to JSON


(optional) Set to .T. to use {...} tags; defaults to .F.


(optional) Set to .T. to remove pretty formatting


(optional) Set to some number of spaces for indented formatting


(optional) Set to .T. to quote property names




Converts an Xbasic variable to a JSON representation.


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 = "selwyn"
p.onchange = "{function}alert('onchange')"
p.onClick = "{function}alert('onclick')"
= name = "selwyn"
onchange = "{function}alert('onchange')"
onClick = "{function}alert('onclick')"

x = varToJSON(p,.f.)
= {
	name: 'selwyn',
	onchange: '{function}alert(\'onchange\')',
	onClick: '{function}alert(\'onclick\')'

y = varToJSON(p,.t.)
= {
	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.

dim p as p
dim p.children[0] as p = "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 = "Smith"

p.myfunc = "Emma"+"Zoe"


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