0

I have problem in parsing the below json to show the desired out on the screen.

Here are the steps I supposed to follow while parsing this json:

1. I have to get the stages array from the json - for example stages ["check_dependency_progress", "shutdown_progress", "backup_progress", "code_upgrade_progress", "start_afresh_progress"],`

2. Get the sub object i.e check_dependency_progress for the first time from above stages array and shutdown_progress second time, and so on..

3. I have to check the step 2 object for status if status === 3 and stages.length > 0 then <li class="parent">object.title</li>

4. If status == 2 get the sub-object from stages array like step 2.

5. if status == 3 found in sub-object then else all

**NOTE:**for convenience you can take "john-22:" to proceed parsing

Here is s jsfiddle: https://jsfiddle.net/eabangalore/uchwz3g5/211/

Here is my solution - not flexible + wrong results + not readable:

var upgradeData = {
  "upgrade": [{
    "status": "UPGRADED",
    "updated_date": "14-02-2018 12:09:25",
    "description": "UPGRADE COMPLETED",
    "hostname": ["john-22", "john-945", "john-9453", "john-1453"],
    "version": "9.2",
    "_id": "5a7aef8407480a589a3a7dd7",
    "john-22": {
      "status": 2,
      "start_afresh_progress": {
        "status": 2,
        "description": "Started back the stopped services.",
        "title": "Starting back the process.",
        "start_back_services": {
          "status": 3,
          "stages": [],
          "description": "Started back the stopped services succesfully !",
          "title": "Starting back the stoped services of MW"
        },
        "restart_webservice": {
          "status": 2,
          "stages": [],
          "description": "Restarting back the WebService.",
          "title": "Restart webservice"
        },
        "stages": ["start_back_services", "restart_webservice"]
      },
      "description": "Upgrading OrangeBell Started !",
      "shutdown_progress": {
        "status": 3,
        "shutdown_mw_progress": {
          "status": 3,
          "stages": [],
          "description": "OrangeBell services are sucessfully shutdown.",
          "title": "Shutting-down OrangeBell services"
        },
        "description": "Completed Shutdown.",
        "title": "Shutdown in Progress.",
        "prepare_shutdown_progress": {
          "status": 3,
          "stages": [],
          "description": "OrangeBell services are prepared to be shutdown.",
          "title": "Shutting-down OrangeBell services"
        },
        "get_current_status_progress": {
          "status": 3,
          "stages": [],
          "description": "OrangeBell services states have been saved.",
          "title": "Getting current state of running services"
        },
        "stages": ["get_current_status_progress", "prepare_shutdown_progress", "shutdown_mw_progress"]
      },
      "stages": ["check_dependency_progress", "shutdown_progress", "backup_progress", "code_upgrade_progress", "start_afresh_progress"],
      "title": "Upgrading OrangeBell",
      "code_upgrade_progress": {
        "status": 3,
        "stages": [],
        "description": "Upgrade Completed Sucessfully!",
        "title": "Upgrading OrangeBell Code"
      },
      "check_dependency_progress": {
        "status": 3,
        "copying_modules_progress": {
          "status": 3,
          "stages": [],
          "description": "Copying necessary modules succesfully !",
          "title": "Copying the modules"
        },
        "description": "Checking of dependency files/packages completed.",
        "title": "Checking the Dependencies",
        "package_dependency_progress": {
          "status": 3,
          "stages": [],
          "description": "Successfully Installed the packages !",
          "title": "Resolving the packages"
        },
        "stages": ["copying_modules_progress", "package_dependency_progress"]
      },
      "backup_progress": {
        "status": 3,
        "stages": [],
        "description": "Backup Completed Sucessfully!",
        "title": "Backup in Progress."
      }
    }
  }]
};
var allChildLi = '';

var allParentLi = '<ul>';

let foundObject = upgradeData.upgrade.map(function(o, i) {

  let objKeys = Object.keys(o);

  return objKeys;
});

var newArray = foundObject[0];

function removeA(arr) {
  var what, a = arguments,
    L = a.length,
    ax;
  while (L > 1 && arr.length) {
    what = a[--L];
    while ((ax = arr.indexOf(what)) !== -1) {
      arr.splice(ax, 1);
    }
  }
  return arr;
}
removeA(newArray, 'status');
removeA(newArray, 'updated_date');
removeA(newArray, 'description');
removeA(newArray, 'hostname');
removeA(newArray, 'version');
removeA(newArray, '_id');

var allUpgradeNode = [];

for (var i = 0; i < newArray.length; i++) {
  var object = upgradeData.upgrade[i][newArray[i]];
  console.log(object);
  var stages = object.stages;
  console.log('stages', stages);

  for (var j = 0; j < stages.length; j++) {
    console.log(object[stages[j]]);

    var childObject = object[stages[j]];

    if (childObject.status == 3) {
      console.log('child description ', childObject.description);
      console.log('child title ', childObject.title);

      allParentLi += '<li>' + childObject.title + '</li>';

    } else {

      for (k = 0; k < childObject.stages.length; k++) {

        var subChildObject = object[stages[k]];

        console.log('sub child ', subChildObject);

        if (subChildObject.status == 3) { // if inside k

          console.log('sub child description ', subChildObject.description);
          console.log('sub child title ', subChildObject.title);

          // allParentLi += '<ul>';

          //allParentLi += '<li class="child">'+subChildObject.description+'</li>';

          //allParentLi += '<li class="child">'+subChildObject.title+'</li>';

          allParentLi += '<li class="child">' + subChildObject.description + '</li>';

        } else { // else inside k

          for (var l = 0; l < subChildObject.stages.length; l++) {

            var subChildCompletionObject = subChildObject[stages[l]];

            console.log('sub sub child completion object', subChildCompletionObject);

            console.log('sub sub child', subChildCompletionObject.description);

            console.log('sub sub child', subChildCompletionObject.title);
          }

        } // endof if inside 

      }


    }

  }

}

allParentLi += '</ul>';

$('#allLi').append(allParentLi);
ul li {
  list-style: none;
  display: block;
  width: 200px;
  height: 45px;
  border: 1px solid red;
  background-color: gray;
  text-align: center;
  position: relative;
  /* i'm unable make text center */
}

ul li.child {
  right: -90px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr/>

<div id="allLi">

</div>
Boris Lobanov
  • 2,409
  • 1
  • 11
  • 19
  • Do you need this to be a tree where each stage has its substages under it? I don't quite understand what the final result should be. – Boris Lobanov Feb 17 '18 at 07:40
  • the final result should be parsing each stage and substage, if stage does not contain substage then it is `parent process` else `substage` would be child process –  Feb 17 '18 at 07:44
  • what if there are several substages like `start_back_services`? It has status 2 and two substages – Boris Lobanov Feb 17 '18 at 07:46
  • more then 3 level it does not go, the api is made in such a way. it would be child process(for `start_back_services` ) –  Feb 17 '18 at 07:48
  • so if the status is 3 we don't loop through the substages? – Boris Lobanov Feb 17 '18 at 07:52
  • if status is 3 then we need not to loop through substages –  Feb 17 '18 at 07:57
  • Have a look at my solution. I assume it works as expected, the inly thing I don't know is whether you want the top node (Upgrading OrangeBell Started ) to be displayed. – Boris Lobanov Feb 17 '18 at 08:22
  • @BorisLobanov, can you please help me with a personal problem, i think you are the only person who can help me, please ping me on this email if you feel to help me `ejazanwar777@gmail.com` –  Jun 25 '18 at 17:14

1 Answers1

1

Here's a recursive solution for walking the tree:

const john22 = upgradeData.upgrade[0]['john-22'];
const stages = john22.stages.map(stage => john22[stage]);

let html = makeNodesList(john22)

$('#allLi').append(html);

function makeNodesList(stageObj) {
    let html = '<ul>';

  if (!(stageObj.status === 2 && stageObj.stages.length)) {
    html += `<li class="child">${stageObj.description}</li>`
  } else {
    html += `<li>${stageObj.description}</li>`
    stageObj.stages.forEach(substage => {
        html +=  makeNodesList(stageObj[substage]);
    })
  }

  html += '</ul>';

  return html;
}

Have a look at the jsfiddle: https://jsfiddle.net/so9eus5r/

UPDATE

Here's the updated jsfiddle based on the comments: https://jsfiddle.net/cLLp10sq/

Boris Lobanov
  • 2,409
  • 1
  • 11
  • 19
  • so nice of you brother i have upvoted, i will verify your answer, thanks alot –  Feb 17 '18 at 08:24
  • sure, let me know if it can be improved – Boris Lobanov Feb 17 '18 at 08:25
  • hello @Boris Lobanov, i confirmed with my api developer , we need to loop through `subobject` whenever there is `length` of **stages** not when `status == 3` i tried to change `if (!(stageObj.stages.length))` –  Feb 17 '18 at 12:35
  • what i'm trying to say is whenever `status == 3` even though we have to check the `stages` **length**. if `stages` **length** is **> 0** then we have to loop through the `subobject` –  Feb 17 '18 at 12:38
  • my desired result should look like this https://drive.google.com/file/d/0B5MchvsFMdatZDd2VTZxVU9QRFh2OGVzT0dlTUhzSVpTbkR3/view?usp=sharing –  Feb 17 '18 at 12:44
  • **PLEASE help me** i tried to from your code but failed to get desired result –  Feb 17 '18 at 12:46
  • I'll look at it when I'm at computer later – Boris Lobanov Feb 17 '18 at 12:48
  • No problem but please help me, thanks alot for your reply –  Feb 17 '18 at 12:49
  • my boss is not believing that you have solved it with so simple manner,with very less code. please have a look at above said problem, thank you very much –  Feb 17 '18 at 14:09
  • there are no words to appreciate your help, thank you very much once again –  Feb 18 '18 at 16:49
  • hi, Boris, please see this question i think you can solve this with very ease https://stackoverflow.com/questions/48910947/how-to-make-desired-json-tree-from-simple-json –  Feb 21 '18 at 16:34
  • hi, I will definitely have a look within 20-30 minutes, I'm commuting right now – Boris Lobanov Feb 21 '18 at 17:13
  • No problem thanks alot, it is similar to previous question, but i was unable to make logic. your last answer saved my job –  Feb 21 '18 at 17:18