JSON Array

 

Recently I had to create a lot of arrays in JSON for the API connection of a webshop.

The filemaker’s own function for creating arrays seems to exist only as a script loop.

From practice my approach would be to pass a list of values to an array command and get a finished array back.

Such a task is ideal for a recursive custom function – I will describe the creation of recursive functions in a separate post.

cf_jsonArray

//cf_jsonArray ( json ; key ; theList ; type , counter )
//type = filemaker type of element
//counter should be inital always 0

Let (

[

max = ValueCount ( theList ) ;

counter = If (counter = “” ; 0 ; counter ) ;

json = JSONSetElement( json ; counter ; GetValue ( theList ; counter +1 ) ; type )

] ;

Case (

max = 0 ; “[]” ;

counter +1 < max ; cf_jsonArray ( json ; key ; theList ; type ; counter + 1 ) ;

counter +1 = max ; JSONSetElement ( “{}” ; [key ; json ; 4] )

)

)

Example call: cf_jsonArray ( “[]“ ;”Images” ; “1.jpg¶2.jpg” ; 1 ; 0 )

In this case the list of images was determined from the relationship of the article images with “List ( Article::Images )”.

Result:

{ „Images“: [ “1.jpg“ , “2.jpg“ ] }

 

Or if the JSON is to be included in an existing JSON, an empty value is passed as key and the result is taken over by JSONRaw into the origin JSON:

JSONFormatElement ( JSONSetElement ( "{}" ;

["Article" ;

JSONSetElement ( "{}" ;

["ArticleShopID" ; 111 ; 2] ;
["Images" ; cf_jsonArray ( "[]" ; "“ ;"1.jpg¶2.jpg" ; 1 ; 0 ) ; JSONRaw ]

) ; JSONObject] )

)

Result:

{
“Article” :
{
“ArticleShopID” : 111 ,
“Images” : [ “1.jpg“ , “2.jpg” ]
}
}

 

You have any questions? Feel free to send me an email, I’ll try to answer as soon as possible.