2009-02-16 17 views
80

Qualcuno può dirmi qual è la differenza tra i 2 parser JSON?Differenza tra json.js e json2.js

https://github.com/douglascrockford/JSON-js/blob/master/json.js
https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Ho un file JSON da 2007-04-13 (ha metodi come parseJSON). Non vedo questi metodi in nessuna delle nuove versioni.

+2

È possibile trovare il nuovo file qui https://github.com/douglascrockford/JSON-js –

+0

Per qualcuno che è venuto a questo chiediti cosa siano questi file, sappi che non c'è motivo di usarli nei browser moderni. Da [GitHub repo] (https://github.com/douglascrockford/JSON-js): "Sui browser correnti, [json2.js] non fa nulla, preferendo l'oggetto JSON integrato. Non c'è motivo di usarlo file a meno che il destino non ti costringa a supportare IE8, che è qualcosa che nessuno dovrebbe mai più fare. " – Thunderforge

risposta

56

Da loro codice:

// Augment the basic prototypes if they have not already been augmented. 
// These forms are obsolete. It is recommended that JSON.stringify and 
// JSON.parse be used instead. 

if (!Object.prototype.toJSONString) { 
    Object.prototype.toJSONString = function (filter) { 
     return JSON.stringify(this, filter); 
    }; 
    Object.prototype.parseJSON = function (filter) { 
     return JSON.parse(this, filter); 
    }; 
} 

Credo parseJSON è obsoleto, quindi, la nuova versione (json2) non ha nemmeno usarlo più. Tuttavia, se il codice utilizza parseJSON molto si può solo aggiungere questo pezzo di codice da qualche parte per farlo funzionare di nuovo:

Object.prototype.parseJSON = function (filter) { 
     return JSON.parse(this, filter); 
    }; 
+1

Grazie, quindi sembra che parseJSON sia stato sostituito da JSON.parse? Inoltre, che dire diJSONString? Il nostro codice esistente utilizza un sacco di questi metodi: boolean.toJSONString() date.toJSONString() number.toJSONString() object.toJSONString() string.toJSONString() –

+0

Quindi aggiungere anche il primo pezzo di codice, tutti i valori specificati sono Oggetti, quindi verranno tutti convertiti per utilizzare automaticamente JSON.stringify. –

+0

Grazie! Darò una prova. Quindi, posso aggiungere queste funzioni al file json.js? –

30

Citando here:

"JSON2.js - Alla fine dello scorso anno Crockford ha rilasciato tranquillamente una nuova versione della sua API JSON che ha sostituito la sua API esistente. L'importante differenza era che utilizzava un singolo oggetto di base. "

20

Ho anche notato che json2 ha un array con stringhe diverso da json2007.

In json2007:

var array = []; 
array[1] = "apple"; 
array[2] = "orange"; 
alert(array.toJSONString()); // Output: ["apple", "orange"]. 

In json2:

var array = []; 
array[1] = "apple"; 
array[2] = "orange"; 
alert(JSON.stringify(array)); // Output: [null, "apple", "orange"]. 
+3

json2 è corretto in questo caso. json2007 ha sbagliato a ignorare il primo elemento all'indice 0. –