AnsweredAssumed Answered

Custom Function to build JSON data for Data API from list of fields

Question asked by skywillmott on Feb 1, 2018
Latest reply on Mar 18, 2018 by jbrown

So I am using the new Data API to insert records into a FMS16 hosted file from a local file in FileMaker Go.


Currently I am using a loop in a script to build up the JSON data that is sent with the Data API 'create record' request that looks something like:


Set Variable [ $fields; Value:FieldNames ( Get(FileName) ; "myLayoutWithFieldsToSend") ]

Set Variable [ $count; Value:ValueCount ( $fields ) ]


     Set Variable [ $i; Value:$i+1 ]
Exit Loop If [ $i>$count ]
Set Variable [ $thisField; Value:GetValue ( $fields ; $i ) ]
Set Variable [ $json; Value:JSONSetElement ( $json ; "data." & $thisField ; GetField ( $thisField ) ; JSONString ) ]

End Loop

Which, if I have a layout called 'myLayoutWithFieldsToSend', with the following fields and values:


Field1 with value 'aa'

Field2 with value 'bb'

Field3 with value 'cc'


... I end up with:

$json = {"data":{"Field1":"aa","Field2":"bb","Field3":"cc"}}


... which is what I want and can send that with the Data API request using 'Insert from URL...'


The nice thing about this is that I can easily pick and choose which fields to place on the 'myLayoutWithFieldsToSend' layout and the $json variable gets built using only those fields so if I choose to add or remove fields from the layout, then the $json variable is always what I want when the script is run as it uses the 'FieldNames' function to get the list of fields on that layout.


However, I would love to replace the loop in the script with a recursive Custom Function that does the job of creating the JSON data from the list of fields on the layout. I have tried to create the Custom Function, but haven't been able to get it working right, so if anybody has any ideas on how to do this I would love to hear about it - thanks :-)