Ho scritto un paio di funzioni che replicano in modo efficace JSON.stringify(), convertendo un intervallo di valori in versioni con stringhe. Quando porto il mio codice su JSBin e lo eseguo su alcuni valori di esempio, funziona perfettamente. Ma sto ottenendo questo errore in un corridore spec progettato per testare questo.Come risolvere TypeError: impossibile convertire undefined o null nell'oggetto
Il mio codice:
// five lines of comments
var stringify = function(obj) {
if (typeof obj === 'function') { return undefined;} // return undefined for function
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (typeof obj === 'number') { return obj;} // number unchanged
if (obj === 'null') { return null;} // null unchanged
if (typeof obj === 'boolean') { return obj;} // boolean unchanged
if (typeof obj === 'string') { return '\"' + obj + '\"';} // string gets escaped end-quotes
if (Array.isArray(obj)) {
return obj.map(function (e) { // uses map() to create new array with stringified elements
return stringify(e);
});
} else {
var keys = Object.keys(obj); // convert object's keys into an array
var container = keys.map(function (k) { // uses map() to create an array of key:(stringified)value pairs
return k + ': ' + stringify(obj[k]);
});
return '{' + container.join(', ') + '}'; // returns assembled object with curly brackets
}
};
var stringifyJSON = function(obj) {
if (typeof stringify(obj) != 'undefined') {
return "" + stringify(obj) + "";
}
};
Il messaggio di errore che sto ricevendo dal tester è:
TypeError: Cannot convert undefined or null to object
at Function.keys (native)
at stringify (stringifyJSON.js:18:22)
at stringifyJSON (stringifyJSON.js:27:13)
at stringifyJSONSpec.js:7:20
at Array.forEach (native)
at Context.<anonymous> (stringifyJSONSpec.js:5:26)
at Test.Runnable.run (mocha.js:4039:32)
at Runner.runTest (mocha.js:4404:10)
at mocha.js:4450:12
at next (mocha.js:4330:14)
Sembra di fallire con: stringifyJSON (null) per esempio
Si prega di fornire l'input per il quale si sta ricevendo errore, in quanto funziona per stringifyJSON ({a: 'b', c: 'd'}) – vinayakj
Oltre all'errore, 'stringifyJSON ([1,2,3]) 'restituisce' 1,2,3' e 'stringifyJSON ({foo: 'bar'})' restituisce '{foo:" bar "}', entrambi i quali non sono JSON validi. –
La mia ipotesi sarebbe questa riga 'if (obj === 'null') {return null;} // null immutato', - che non passerà quando viene dato' null', solo se data la stringa '" null " '. Quindi se si passa il valore reale 'null' al proprio script, esso verrà analizzato nella parte Object del codice. E 'Object.keys (null)' indica il 'TypeError' menzionato. Per risolverlo, usa 'if (obj === null) {return null}' - senza il qoutes attorno a 'null'. – veproza