Skip to Content

JSON Simple Transformation Array/Object

I have JSON file where the values are sometimes an array and sometimes the file treats it as an object. The logic creating the JSON file seems to make it an object when only one value exists for the object else it makes it an array.

Sometimes Generic is Object

"Generic": { "ActivityType": "DS", "TrackingNumber": "XXXXXX", "ShipperNumber": "99999" }

Sometimes Generic is an Array

"Generic": [ { "ActivityType": "DS", "TrackingNumber": "XXXX", "ShipperNumber": "99999" } , { "ActivityType": "DS", "TrackingNumber": "YYYYY", "ShipperNumber": "99999" } ]


Please note this happens within the same json file.


Using a simple transformation, how do I put in a test to see which one it should be?

<object name="Generic">

<array name="Generic">


Thanks for any help.


Add comment
10|10000 characters needed characters exceeded

  • Follow
  • Get RSS Feed

1 Answer

  • Sep 21, 2018 at 04:24 PM
    I am thinking some code like below would solve the issue, but I have to replicate the a routine like PackageRef_Set for each different name that has the issue.  Wonder if there is a more generic solution for it.  Like a way to call the setmembers dynamically from a parameter passed in.
    
      <tt:template name="PackageRef_Set">
        <tt:cond check="exist($ref.PACKAGEREFERENCENUMBER)">
          <tt:cond>
            <object name="PackageReferenceNumber">
              <tt:apply name="PackageRef_SetMembers"/>
            </object>
          </tt:cond>
          <tt:cond>
            <array name="PackageReferenceNumber">
              <tt:loop ref="PACKAGEREFERENCENUMBER">
                <object>
                  <tt:apply name="PackageRef_SetMembers"/>
                </object>
              </tt:loop>
            </array>
          </tt:cond>
        </tt:cond>
      </tt:template>
    
      <tt:template name="PackageRef_SetMembers">
        <tt:cond check="exist($ref.BARCODEINDICATOR)">
          <str name="BarCodeIndicator" tt:value-ref="BARCODEINDICATOR"/>
        </tt:cond>
        <tt:cond check="exist($ref.NUMBER)">
          <str name="Number" tt:value-ref="NUMBER"/>
        </tt:cond>
        <tt:cond check="exist($ref.CODE)">
          <str name="Code" tt:value-ref="CODE"/>
        </tt:cond>
        <str name="Value" tt:value-ref="VALUE"/>
      </tt:template>
    
    
    
    Add comment
    10|10000 characters needed characters exceeded