Im leggere tra le righe qui e indovinando che si desidera che il valore non sia definito quando si utilizza JSON.parse?
Se questo è il caso è possibile utilizzare il seguente:
var encodeUndefined = function(obj, undefinedPaths, path) {
path = path || 'ROOT';
for (var key in obj) {
var keyPath = path + '.' + key;
var value = obj[key];
if (value === undefined) {
undefinedPaths.push(keyPath);
} else if (typeof value == "object" && value !== null) {
encodeUndefined(obj[key], undefinedPaths, keyPath);
}
}
}
var stringifyAndPreserveUndefined = function(obj) {
var undefinedPaths = [];
//save all paths that have are undefined in a array.
encodeUndefined((obj), undefinedPaths);
return JSON.stringify({
ROOT: obj,
undefinedPaths: undefinedPaths
}, function(k, v) { if (v === undefined) { return null; } return v; });
}
var parseAndRestoreUndefined = function(value) {
var data = JSON.parse(value);
var undefinedPaths = data.undefinedPaths;
var obj = data.ROOT;
//Restore all undefined values
for (var pathIndex = 0; pathIndex < undefinedPaths.length; pathIndex++) {
var pathParts = undefinedPaths[pathIndex].substring(5).split('.');
var item = obj;
for (var pathPartIndex = 0; pathPartIndex < pathParts.length - 1; pathPartIndex++) {
item = item[pathParts[pathPartIndex]];
}
item[pathParts[pathParts.length - 1]] = undefined;
}
return obj;
}
var input = {
test1: 'a',
test2: 'b',
test3: undefined,
test4: {
test1: 'a',
test2: undefined
}
};
var result = stringifyAndPreserveUndefined(input);
var result2 = parseAndRestoreUndefined(result);
stringifyAndPreserveUndefined
codificherà tutti i valori non definiti in un array e quando si chiama parseAndRestoreUndefined
li metterà nel posto giusto ancora una volta.
L'unico lato negativo è che Json non assomiglierà esattamente all'oggetto. Nell'esempio sopra si trasformerà in {"ROOT":{"test1":"a","test2":"b","test4":{"test1":"a"}},"undefinedPaths":["ROOT.test3","ROOT.test4.test2"]}
JSON non ha un valore indefinito. Cosa vuoi? – SLaks
Dovresti cambiare il valore nella stringa '" undefined "' o forse 'null' o una stringa vuota' "" '. Come preferiresti? –
Scopri http://json.org/ Si noti che nel valore standard può essere 'stringa',' numero', 'oggetto',' matrice', 'vero',' falso' o 'null'. Si noti che 'undefined' non è un'opzione. –