Create multi level JSON dynamically

I created a new CFC for accessing the new UPS API using JSON. I mainly use the rates API which sends a slight big and multi level JSON. I decided to go with creating a struct and then serialize it to JSON. Works great except the keys need to be case sensitive, so the struct is built like an array (struct[“Key”][“Subkey”]…etc). I looked at components but you would need a bunch of them to make all the layers and it seems to be more confusing than the struct.

Anyone done anything like this and have any better input?

You can see my struct based CFC and example at https://github.com/kabutotx/upsapi

you can set Lucee globally do not make dot notation variables uppercase under settings/language compiler in the Lucee admin or set the following for the current template (cfm or cfc)

<cfprocessingdirective preserveCase="false">
<!--- or --->
<cfscript>processingdirective preserveCase="false";</cfscript>

Just for some more options, you can also pass that in as a JVM argument:

-Dlucee.preserve.case=true

I believe that is doing the same thing?

1 Like

You could build a struct using “literal syntax” rather than array notation.

Here’s an example from the Ortus book (modified to create an ordered struct):

produce = [
    "grapes": 2,
    "lemons": 1,
    "eggplants": 6
];

I develop for both ACF & Lucee and intentionally use quoted keys as I never know what the environment’s (or application’s) preverseCase setting is going to be (or if the setting is supported.)

If you use an ordered struct, you can retain a desired key order. Some pseudo-JSON gateways explicitly require the data to be in the exact same order as XML as they act as a proxy to an older, internal XML gateway. (I’ve encountered this before, but forget which 3rd party API it was.) I also find that it’s easier to debug if the struct keys are in a logical order.

4 Likes