dimanche 2 octobre 2016

Iterate through entire JSON object without knowing any keys

I'm attempting to perform operations (update values, delete keys, add keys, etc.) on JSON objects which I do not know anything about. These items are essentially property files and not JSON data returned from an application. These files could be very different and I need to develop a method that can perform these operations without knowing anything about the JSON data.

I am keeping track of the path of where the key is stored. If I had sample data as shown below, I would store the path like '/key1/innerKey5/' and get the data with the key innerKey6 using getNodeData.

If I had the path and the key of the item I need to delete, how can I programmatically find this item in the JSON object and delete or update the item?

var originalData = someMethodToGetJSONData();
var currentData; // Global variable storing a copy of the original data which can be modified

json = {
  "key1": {
    "innerKey1": {
      "innerKey2" : {
        "innerKey3": "value1",
        "innerKey4": "value2"
      }
    },
    "innerKey5": {
      "innerKey6": "value1"
    }
  },
  "key2": "value3",
  "key3": "value4"
}

function getKeysFromPath(keyPath) {
  var split = keyPath.split('/');
  var keys = [];

  for(var i = 0; i < split.length; i++) {
    if(split[i] != '') {
      keys.push(split[i]);
    }
  }

  return keys
}

function getNodeData(keyPath) {
  var keys = getKeysFromPath(keyPath);
  nodeData = currentItemData;

  for(var i = 0; i < keys.length; i++) {
    nodeData = nodeData[keys[i]];
  }

  return nodeData;
}

data = getNodeData('/key1/innerKey5/');
key = 'innerKey6';
console.log('Data: ' + data[key]);




Aucun commentaire:

Enregistrer un commentaire