Convert coldfusion json to struct

大憨熊 提交于 2019-12-04 03:52:44

In JSON, the [] denotes an array and {} a structure (or object). So your input is actually an array of structures. You need to use an array loop, not a collection loop:

<cfset arrayOfStructs = deserializeJson(output)>
<cfloop array="#arrayOfStructs#" index="parent">
      <cfset parentID = parent.id />
      ... 
</cfloop>

children is also an array of structures. Inside the outer loop, check for the existence of that key. If found, loop through the child array and do something with each of the id's:

  <cfif structKeyExists(parent, "children")>
      <cfloop array="#parent.children#" index="child">
          ...
      </cfloop>
  </cfif>

A tidy cfscript version. :)

<cfscript>
    structObj = deserializeJson(jsonString);

    for(i = 1; i LTE ArrayLen(structObj); i++){

        WriteOutput("parent id : " & structObj[i].id & "<br>"); 
        if(StructKeyExists(structObj[i], "children")){
            for(j = 1; j LTE ArrayLen(structObj[i].children); j++){
                WriteOutput("    -children id : " & structObj[i].children[j].id & "<br>");
            }
        }
    }
</cfscript>

I created an Angular 1.4 ColdFusion 9 JSON Normalizer here

 var myURL = 'myCfc.cfc?method=getItemsFromDb';
 var app = angular.module('angularOutput',[]);
 app.controller("sectionController", function($scope, $http) {
      $http.get(myURL).
        success(function(data, status, headers, config) {
          var log = []; 
          var output = '';
          angular.forEach(data.DATA, function(value, key) {
                    this.push(output +='{"value": ');
                    this.push(output += '"'+value[0]+'"');
                    this.push(output +=',"text":');
                    this.push(output += '"'+value[1]+'"');
                    this.push(output +='}');
                    this.push(output +=',');
                }, log);
              output = output.replace(/,\s*$/, "");/*had to remove the final comma */
              output = '['+output+']'; /*had to add the [] to corectally form the output*/

          $scope.sections = angular.fromJson(output);
        }).
        error(function(data, status, headers, config) {
          console.log(data);
        });
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!