2014-10-24 16 views
25

Come conservare i valori non definiti quando si esegue JSON.stringify (hash)?Preservazione non definita che JSON.stringify rimuove altrimenti

Ecco un esempio:

var hash = { 
    "name" : "boda", 
    "email" : undefined, 
    "country" : "africa" 
}; 

var string = JSON.stringify(hash); 

> "{"name":"boda","country":"africa"}" 

Email scomparso dalla JSON.stringify.

+11

JSON non ha un valore indefinito. Cosa vuoi? – SLaks

+4

Dovresti cambiare il valore nella stringa '" undefined "' o forse 'null' o una stringa vuota' "" '. Come preferiresti? –

+3

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. –

risposta

6

Utilizzare null anziché undefined.

var hash = { 
    "name" : "boda", 
    "email" : null, 
    "country" : "africa" 
}; 

var string = JSON.stringify(hash); 

> "{"name":"boda","email":null,"country":"africa"}" 
42

È possibile passare una funzione sostituto per JSON.stringify per convertire automaticamente undefined valori null valori, in questo modo:

var string = JSON.stringify(
    obj, 
    function(k, v) { if (v === undefined) { return null; } return v; } 
); 

Questo funziona per valori non definiti all'interno multidimensionali, come JSON.stringify già converte quelli null.

+4

ES6: 'JSON.stringify (obj, (k, v) => v === undefined? null: v)' – ricka

+1

mentre questo è una soluzione che non risolve il problema in quanto non conserva il valore come non definito, lo modifica in null. – Peter

+0

@Peter JSON consente solo valori 'null', non esiste alcun valore' indefinito' definito nello standard JSON. – Flimm

1

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"]}

+1

Soluzione lunga, ma funziona almeno. (nel mio caso, io uso solo l'approccio "converti in null", dal momento che non ho bisogno di conservarlo in json come "non definito") – Venryx

0
function stringifyWithUndefined(obj, space) { 
    const str = JSON.stringify(obj, (key, value) => value === undefined ? '__undefined__' : value, space); 
    return str.replace(/"__undefined__"/g, 'undefined'); 
} 

Esempio:

const obj = { 
    name: 'boda', 
    email: undefined, 
    country: 'africa' 
}; 
console.log(stringifyWithUndefined(obj, 2)); 

risultati:

{ 
    "name": "boda", 
    "email": undefined, 
    "country": "africa" 
}