« FileMaker 13 | Home | BKeeney Software is h… »

Generate JSON with MBS Plugin

A client asked for help with the following JSON.

{"ticket":{"requester":{"name":"The Customer", "email":"thecustomer@domain.com"}, "subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}

As you see we have several levels deep nesting which may be confusion. But the goal is to work from inside to outside to make bigger blocks. First we start with an empty object, than we add the comment entry. Now we add there the entries for the requester section. Than we build the ticket section with requester, subject and comment entries. Finally be put that into a new object with ticket entry:

$jempty = MBS( "JSON.CreateObject")
$jcomment = MBS( "JSON.AddStringToObject"; $jempty; "body"; "The smoke is very colorful." )
$jrequester = MBS( "JSON.AddStringToObject"; $jempty; "name"; "The Customer" )
$jrequester = MBS( "JSON.AddStringToObject"; $jrequester; "email"; "thecustomer@domain.com" )
$jticket = MBS( "JSON.AddItemToObject"; $jempty; "requester"; $jrequester)
$jticket
= MBS( "JSON.AddStringToObject"; $jticket; "subject";"My printer is on fire!" )
$jticket = MBS( "JSON.AddItemToObject"; $jticket; "comment"; $jcomment)
$j
= MBS( "JSON.AddItemToObject"; $jempty; "ticket"; $jticket)

optional a call to MBS("JSON.Compact"; $j) for a more compact representation. Normally we use the human readable representation with more spaces and indention.

For debugging all those variables contain the intermediate JSON stings, so you can easily see what happens. And if you have common JSON you reuse, be sure to actually reuse the variables like we do with $jempty here.
03 12 13 - 23:02