2016-10-02 87 views
3

我試圖對JSON數據執行操作(更新值,刪除鍵,添加鍵等),這些我都不知道。這些項目實際上是屬性文件,而不是從應用程序返回的JSON數據。這些文件可能會非常不同,我需要開發一種方法,可以在不瞭解JSON數據的情況下執行這些操作。在不知道任何鍵的情況下遍歷整個JSON對象

我跟蹤密鑰存儲位置的路徑。如果我有如下所示的樣本數據,我會將路徑存儲爲'/ key1/innerKey5 /',並使用getNodeData獲取具有密鑰innerKey6的數據。

如果我有項目的路徑和密鑰,如何以編程方式在JSON數據中找到此項目並刪除或更新項目?

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]); 
+1

忌諱:JSON對象只有兩個屬性:'parse'和'stringify'。你有一個* JavaScript對象*,或者只是一個*對象*,而不是一個JSON對象。 – Amadan

+0

看看使用[Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) – charlietfl

+0

@Amadan你是對的,謝謝。 –

回答

0

Lodash對做這類事情有一些有用的功能。

_.get,_.set,_.unset

所以,如果要存儲節點串形式,例如。 - > a.b.c [0] .k,這3個函數應該可以做你想做的。

+0

這看起來是最快最簡單的選擇。謝謝。 –

0

如果您在使用jQuery使用。每個()函數:

$.each(json,function(key,val){ 
     //You may use key/val for every iteration 
}); 
0

爲了更新或刪除,則需要獲得父對象和最後的關鍵:

var lastKey = keys.pop(); 
var parentObj = getNodeByKeys(keys); // refactor your code to make this function 
parentObj[lastKey] = newValue; 
delete parentObj[lastKey]; 
1

這是如何通過未知鍵迭代

var key; 

for (key in arr) { 
    if (arr.hasOwnProperty(key)) { 
    console.log(key); 
    console.log(arr[key]); 
    } 
} 
0

獲取經由XHR數據和解析JSON一個例子:

var getJSON = function(url) { 
    return new Promise(function(resolve, reject) { 
     var xhr = new XMLHttpRequest(); 
     xhr.open('get', url, true); 
     xhr.onload = function() { 
      var status = xhr.status; 
      if (status == 200) { 
       resolve(JSON.parse(xhr.response)); 
      } else { 
       reject(status); 
      } 
     }; 
     xhr.send(); 
    }); 
}; 

然後使用jQuery each

getJSON('//yoursite.com/yourfile.json').then(function(data) { 
    $.each(data, function(k, v) { 
     console.log(k + ', ' + v); 
    }); 
}, function(status) { 
    console.log(status); 
}); 
+0

如果你打算拋出jQuery來使用'each',爲什麼不使用'$ .getJSON'呢? – charlietfl

+0

是的。我發現原生的JS XHR很容易跨界瀏覽(wES6 shim),但發現在本地JS中迭代對象並不平凡。所以'$ .each'很容易跨瀏覽器。我的首選是原生JS,就是這樣。 –

+0

在原生JS中你可以這樣做:'Object.keys(json).forEach(function(key){});'。幾乎和jQuery一樣。 –

0

您可以使用此功能從「路徑」獲取數據:

/** 
* Get a node from an object according to the given path. 
* @param {String} path Node's path. 
* @param {Object} data Object to retrieve the desired information. 
* @returns {Object} Returns the value from the node, or null in the 
* case the node is not found. 
*/ 
function getNode(path, data) 
{ 
    var currentNode = data; 

    path.replace(/^\/|\/$/g, '').split('/').forEach(function(key){ 
     if(key in currentNode) 
     { 
      currentNode = currentNode[key]; 
     } 
     else 
     { 
      currentNode = null; 
      return false; 
     } 
    }); 

    return currentNode; 
} 

從那裏,你可以操縱你的對象是這樣的:

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

var someNode = getNode('/key1/innerKey5', myData); 

// add value 
someNode.innerKey7 = 'newValue'; 

// update existing value 
someNode.innerKey7 = 'otherValue'; 

// delete value 
delete someNode.innerKey6; 

console.log(myData); 
相關問題