Skip to content

Instantly share code, notes, and snippets.

@fsans
Last active December 13, 2023 18:22
Show Gist options
  • Save fsans/8dd949e913e48d9beed5bdfbfba830e1 to your computer and use it in GitHub Desktop.
Save fsans/8dd949e913e48d9beed5bdfbfba830e1 to your computer and use it in GitHub Desktop.
FileMaker Custom Function that spreads all json nodes as script variables

JSON.toVars

FileMaker Custom Function that spreads all json nodes as script variables.

WARNING:

This function is developed with Scriptparameter parsing in mind, so will streamline to most useful parameter parsing options for better use in FileMaker Scripts

WARNING:

Still under developmment (but working great)

Dependencies:

JSON.IsValid(_value) (only a simple wrapper to check against "?")
Take a look to VarArrayToList that will further help a lot.

USE:

JSON.toVars( json; namespace )

with

_json = { 
    "estate":{
        "id":"123", 
        "name":"foo"
        }, 
    "foo":12345,
    "var":true, 
    "arr":["A","B"] 
    }

will return (and sets these variables)

$p.estate.id 	(set to -> 123 )  
$p.estate.name 	(set to -> foo )  
$p.foo 			(set to -> 12345 )  
$p.var 			(set to -> 1 )  
$p.arr.0 		(set to -> A )  
$p.arr.1		(set to -> B )  
  • use $ + namespace to set global scope ($$p.)
  • Default namespace is "p" and set in local scope ( $p.), use as many namespaces as required in the same scope to avoid variable overriding, either local or global scope
  • Forget real multidemensional arrays since filemaker repeated variables does not exists

To handle the splited arrays ( $p.arr.0…n ) please use this helper CF VarArrayToList()

TODO: parse arrays (in progress)
-> returning a FM list may be a better/practical option ?
-> $p.foo.0…n or $p.foo[0…n] ?

Let(
[
	_namespace = Case( IsEmpty( namespace ); "p"; namespace);
	_namespace = Substitute( _namespace; "$$"; "$" );
	_json= json;
	_nodes = JSONListKeys( _json; "." )
];
While( 
[ 
	_n = 1; _debug = True;
	_stack = "";
	_max = ValueCount ( _nodes )
]; 
	_n <= _max ;
[ 
	_name = GetValue( _nodes; _n );
	_value = JSONGetElement( _json ; _name );
	_param = "$" & _namespace & "." & Substitute(_name;"-";"_");
	_isJson = JSON.IsValid(_value);
	_isArray = _isJson and Left( _value; 1 ) = "["; 
	_new = Case(_isJson;

				JSON.toVars( _value; _namespace & "." & Substitute(_name;"-";"_") );

				/* NOT JSON (SO NOR ARRAY), GET THE VALUE */
				Let([
						_expression = "Let(" & _param & "=" & Quote(_value) & ";\"\")";
						_null = Evaluate( _expression ) 
					];
					_param & Case(_debug; " -> " & _value )
				)
				
			);

	_stack = List( _stack; _new ); 
	_n = 1+_n	
];
	_stack
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment