json_parse Function


dim result as p = json_parse(jsonTxt as C [, flagJavascriptSyntax as L])



JSON formatted text.


Default = .f.. If the JSON string contains Javascript function definitions, this parameter must be set to .t., otherwise json_parse() may fail to parse the JSON.



Returns the JSON parsed as a dot variable.


The json_parse function parses a string in JSON format and returns an Xbasic dot variable.


JSON parse is one of the most important functions for dealing with JSON in Xbasic. The json_parse function parses a string in JSON format and returns an Xbasic dot variable. Keep in mind that Xbasic is case in-sensitive so if the JSON you are parsing has duplicate property names (with different cases), the resulting Xbasic dot variable will only have a single instance of the property.

? json_parse("{ foo : 1}")
= foo = 1

Json_parse can handle this incorrectly formatted json, i.e. JSON spec requires names be quoted. The json_parse() function can take an optional second argument to indicate if the JSON being parsed is a Javascript object literal rather than a JSON string. For example, the json_parse() function can interpret Javascript Date() functions in a JSON string. This allows you to parse JSON strings generated by the json_generate() function, if the json_generate() function generated a JSON string that uses the Date() function.

dim p as p 
p.name = "Fred" 
p.sayHello = "{javascript}function() { alert('hello');}"

Now, generate a Javascript object literal. Pass in .t. as the second argument to vartojson() to indicate that we want an Javascript object literal and not a JSON string.

dim jsObject as c 
jsObject = vartojson(p,.t.)

Here is what the resulting string looks like:

	name: 'Fred',
	sayHello: function() { alert('hello');}

Now, in order to be able to parse this object literal back to Xbasic, we use the json_parse() function but we set the optional second argument to .t.

dim pj as p
pj = json_parse(jsObject, .t.)
= "Fred"

= "{javascript}function() { alert('hello');}"
p2 = json_parse("[{name:\"Fred Smith\", age: 23 },{name:\"John Jones\", age: 45}]")

= age = 23
name = "Fred Smith"

= age = 45
name = "John Jones"

The following example shows a round trip using json_parse() and json_generate() to show how date and time values are preserved.

dim p1 as p
p1.name = "Karen"
p1.dob = date()
p1.time = now()

? json_generate(p1)
	"name": "Karen",
	"dob": Date('2016/10/26'),
	"time": Date('2016/10/26T23:52:28:130')

dim jsonTxt as c
jsonTxt = json_generate(p1)
dim p2 as p
p2 = json_parse(jsonTxt)

= dob = {10/26/2016}
name = "Karen"
time = 10/26/2016 11:52:28 13 pm

See Also