diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/it/web/javascript/reference/global_objects/json | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/it/web/javascript/reference/global_objects/json')
3 files changed, 695 insertions, 0 deletions
diff --git a/files/it/web/javascript/reference/global_objects/json/index.html b/files/it/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..caa08b766f --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,244 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>JSON</code></strong> object contains methods for parsing <a class="external" href="http://json.org/">JavaScript Object Notation</a> ({{glossary("JSON")}}) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.</p> + +<h2 id="Description">Description</h2> + +<h3 id="JavaScript_Object_Notation">JavaScript Object Notation</h3> + +<p>JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and {{jsxref("null")}}. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. See also <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">JSON: The JavaScript subset that isn't</a>.</p> + +<table> + <caption>JavaScript and JSON differences</caption> + <thead> + <tr> + <th scope="col">JavaScript type</th> + <th scope="col">JSON differences</th> + </tr> + </thead> + <tbody> + <tr> + <td>Objects and Arrays</td> + <td>Property names must be double-quoted strings; trailing commas are forbidden.</td> + </tr> + <tr> + <td>Numbers</td> + <td>Leading zeros are prohibited; a decimal point must be followed by at least one digit.</td> + </tr> + <tr> + <td>Strings</td> + <td> + <p>Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (<a href="http://unicode-table.com/en/2028/">U+2028</a>) and paragraph separator (<a href="http://unicode-table.com/en/2029/">U+2029</a>) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:</p> + + <pre class="brush: js"> +var code = '"\u2028\u2029"'; +JSON.parse(code); // works fine +eval(code); // fails +</pre> + </td> + </tr> + </tbody> +</table> + +<p>The full JSON syntax is as follows:</p> + +<pre><var>JSON</var> = <strong>null</strong> + <em>or</em> <strong>true</strong> <em>or</em> <strong>false</strong> + <em>or</em> <var>JSONNumber</var> + <em>or</em> <var>JSONString</var> + <em>or</em> <var>JSONObject</var> + <em>or</em> <var>JSONArray</var> + +<var>JSONNumber</var> = <strong>-</strong> <var>PositiveNumber</var> + <em>or</em> <var>PositiveNumber</var> +<var>PositiveNumber</var> = DecimalNumber + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> + <em>or</em> <var>DecimalNumber</var> <strong>.</strong> <var>Digits</var> <var>ExponentPart</var> + <em>or</em> <var>DecimalNumber</var> <var>ExponentPart</var> +<var>DecimalNumber</var> = <strong>0</strong> + <em>or</em> <var>OneToNine</var> <var>Digits</var> +<var>ExponentPart</var> = <strong>e</strong> <var>Exponent</var> + <em>or</em> <strong>E</strong> <var>Exponent</var> +<var>Exponent</var> = <var>Digits</var> + <em>or</em> <strong>+</strong> <var>Digits</var> + <em>or</em> <strong>-</strong> <var>Digits</var> +<var>Digits</var> = <var>Digit</var> + <em>or</em> <var>Digits</var> <var>Digit</var> +<var>Digit</var> = <strong>0</strong> through <strong>9</strong> +<var>OneToNine</var> = <strong>1</strong> through <strong>9</strong> + +<var>JSONString</var> = <strong>""</strong> + <em>or</em> <strong>"</strong> <var>StringCharacters</var> <strong>"</strong> +<var>StringCharacters</var> = <var>StringCharacter</var> + <em>or</em> <var>StringCharacters</var> <var>StringCharacter</var> +<var>StringCharacter</var> = any character + <em>except</em> <strong>"</strong> <em>or</em> <strong>\</strong> <em>or</em> U+0000 through U+001F + <em>or</em> <var>EscapeSequence</var> +<var>EscapeSequence</var> = <strong>\"</strong> <em>or</em> <strong>\/</strong> <em>or</em> <strong>\\</strong> <em>or</em> <strong>\b</strong> <em>or</em> <strong>\f</strong> <em>or</em> <strong>\n</strong> <em>or</em> <strong>\r</strong> <em>or</em> <strong>\t</strong> + <em>or</em> <strong>\u</strong> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> <var>HexDigit</var> +<var>HexDigit</var> = <strong>0</strong> through <strong>9</strong> + <em>or</em> <strong>A</strong> through <strong>F</strong> + <em>or</em> <strong>a</strong> through <strong>f</strong> + +<var>JSONObject</var> = <strong>{</strong> <strong>}</strong> + <em>or</em> <strong>{</strong> <var>Members</var> <strong>}</strong> +<var>Members</var> = <var>JSONString</var> <strong>:</strong> <var>JSON</var> + <em>or</em> <var>Members</var> <strong>,</strong> <var>JSONString</var> <strong>:</strong> <var>JSON</var> + +<var>JSONArray</var> = <strong>[</strong> <strong>]</strong> + <em>or</em> <strong>[</strong> <var>ArrayElements</var> <strong>]</strong> +<var>ArrayElements</var> = <var>JSON</var> + <em>or</em> <var>ArrayElements</var> <strong>,</strong> <var>JSON</var> +</pre> + +<p>Insignificant whitespace may be present anywhere except within a <code><var>JSONNumber</var></code> (numbers must contain no whitespace) or <code><var>JSONString</var></code> (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (<a href="http://unicode-table.com/en/0009/">U+0009</a>), carriage return (<a href="http://unicode-table.com/en/000D/">U+000D</a>), line feed (<a href="http://unicode-table.com/en/000A/">U+000A</a>), and space (<a href="http://unicode-table.com/en/0020/">U+0020</a>) characters are the only valid whitespace characters.</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("JSON.parse()")}}</dt> + <dd>Parse a string as JSON, optionally transform the produced value and its properties, and return the value.</dd> + <dt>{{jsxref("JSON.stringify()")}}</dt> + <dd>Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.</dd> +</dl> + +<h2 id="Polyfill">Polyfill</h2> + +<p>The <code>JSON</code> object is not supported in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>JSON</code> object in implementations which do not natively support it (like Internet Explorer 6).</p> + +<p>The following algorithm is an imitation of the native <code>JSON</code> object:</p> + +<pre class="brush: js">if (!window.JSON) { + window.JSON = { + parse: function(sJSON) { return eval('(' + sJSON + ')'); }, + stringify: (function () { + var toString = Object.prototype.toString; + var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; + var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'}; + var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); }; + var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g; + return function stringify(value) { + if (value == null) { + return 'null'; + } else if (typeof value === 'number') { + return isFinite(value) ? value.toString() : 'null'; + } else if (typeof value === 'boolean') { + return value.toString(); + } else if (typeof value === 'object') { + if (typeof value.toJSON === 'function') { + return stringify(value.toJSON()); + } else if (isArray(value)) { + var res = '['; + for (var i = 0; i < value.length; i++) + res += (i ? ', ' : '') + stringify(value[i]); + return res + ']'; + } else if (toString.call(value) === '[object Object]') { + var tmp = []; + for (var k in value) { + if (value.hasOwnProperty(k)) + tmp.push(stringify(k) + ': ' + stringify(value[k])); + } + return '{' + tmp.join(', ') + '}'; + } + } + return '"' + value.toString().replace(escRE, escFunc) + '"'; + }; + })() + }; +} +</pre> + +<p>More complex well-known <a class="external" href="http://remysharp.com/2010/10/08/what-is-a-polyfill/">polyfills</a> for the <code>JSON</code> object are <a class="link-https" href="https://github.com/douglascrockford/JSON-js">JSON2</a> and <a class="external" href="http://bestiejs.github.com/json3">JSON3</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json-object', 'JSON')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("8.0")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("4.0")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Date.prototype.toJSON()")}}</li> +</ul> diff --git a/files/it/web/javascript/reference/global_objects/json/parse/index.html b/files/it/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..f5c823ddf1 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,126 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +tags: + - ECMAScript5 + - JSON + - JavaScript + - Riferimento + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">Il metodo <strong><code>JSON.parse()</code></strong> analizza una stringa JSON, costruendo il valore JavaScript o l'oggetto descritto dalla stringa. È possibile fornire una funzione <strong>reviver</strong> opzionale per eseguire una trasformazione sull'oggetto risultante prima che venga restituito.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/json-parse.html")}}</div> + + + +<h2 id="Sintassi">Sintassi</h2> + +<pre class="syntaxbox">JSON.parse(<var>text</var>[, <var>reviver</var>])</pre> + +<h3 id="Parametri">Parametri</h3> + +<dl> + <dt><code>text</code></dt> + <dd>La stringa da analizzare come JSON. Vedi l'oggetto {{jsxref("JSON")}} per una descrizione della sintassi JSON.</dd> + <dt><code>reviver</code> {{optional_inline}}</dt> + <dd>Se una funzione, questo prescrive come viene trasformato il valore originariamente prodotto dall'analisi, prima di essere restituito.</dd> +</dl> + +<h3 id="Valore_di_ritorno">Valore di ritorno</h3> + +<p>{{jsxref("Object")}} corrispondente al parametro JSON <code>text</code> dato.</p> + +<h3 id="Eccezione">Eccezione</h3> + +<p>Genera un errore {{jsxref("SyntaxError")}} se la stringa da analizzare non è JSON valida.</p> + +<h2 id="Esempi">Esempi</h2> + +<h3 id="Utilizzare_JSON.parse()">Utilizzare <code>JSON.parse()</code></h3> + +<pre class="brush: js">JSON.parse('{}'); // {} +JSON.parse('true'); // true +JSON.parse('"foo"'); // "foo" +JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] +JSON.parse('null'); // null +</pre> + +<h3 id="Usare_il_parametro_reviver">Usare il parametro <code>reviver</code></h3> + +<p>Se viene specificato un <code>reviver</code>, il valore calcolato dall'analisi viene trasformato prima di essere restituito. In particolare, il valore calcolato e tutte le sue proprietà (che iniziano con le proprietà più nidificate e procedono al valore originale stesso) vengono eseguite individualmente attraverso il <code>reviver</code>. Quindi viene chiamato, con l'oggetto contenente la proprietà da elaborare come <code>this</code>, e con il nome della proprietà come stringa e il valore della proprietà come argomenti. Se la funzione <code>reviver</code> restituisce {{jsxref("undefined")}} (o non restituisce alcun valore, ad esempio, se l'esecuzione cade al termine della funzione), la proprietà viene cancellata dall'oggetto. In caso contrario, la proprietà viene ridefinita come il valore restituito.</p> + +<p>Se <code>reviver</code> trasforma solo alcuni valori e non altri, sii certo di restituire tutti i valori non trasformati così come sono, altrimenti verranno eliminati dall'oggetto risultante.</p> + +<pre class="brush: js">JSON.parse('{"p": 5}', (key, value) => + typeof value === 'number' + ? value * 2 // ritorna: value * 2 per i numeri + : value // restituisce tutto il resto invariato +); + +// { p: 10 } + +JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => { + console.log(key); // registra il nome della proprietà corrente, l'ultimo è "". + return value; // restituisce il valore della proprietà invariato. +}); + +// 1 +// 2 +// 4 +// 6 +// 5 +// 3 +// "" +</pre> + +<h3 id="JSON.parse()_non_consente_virgole_finali"><code>JSON.parse()</code> non consente virgole finali</h3> + +<pre class="example-bad brush: js example-bad">// both will throw a SyntaxError +JSON.parse('[1, 2, 3, 4, ]'); +JSON.parse('{"foo" : 1, }'); +</pre> + +<h2 id="Specifiche">Specifiche</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specifica</th> + <th scope="col">Stato</th> + <th scope="col">Commento</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definizione iniziale. Implementato in JavaScript 1.7.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatiblità_con_i_browser">Compatiblità con i browser</h2> + +<div> + + +<p>{{Compat("javascript.builtins.JSON.parse")}}</p> +</div> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<ul> + <li>{{jsxref("JSON.stringify()")}}</li> +</ul> diff --git a/files/it/web/javascript/reference/global_objects/json/stringify/index.html b/files/it/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..9a0bf5f812 --- /dev/null +++ b/files/it/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,325 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +<div>{{JSRef}}</div> + +<div> </div> + +<p>Il metodo <strong><code>JSON.stringify()</code></strong> converte un oggetto o un valore JavaScript in una stringa JSON, sostituendo facoltativamente i valori se viene specificata una funzione sostitutiva o facoltativamente includendo solo le proprietà specificate se viene specificato un array replacer.</p> + +<div>{{EmbedInteractiveExample("pages/js/json-stringify.html")}}</div> + + + +<h2 id="Sintassi">Sintassi</h2> + +<pre class="syntaxbox"><code>JSON.stringify(<var>value</var>[, <var>replacer</var>[, <var>space</var>]])</code></pre> + +<h3 id="Parametri">Parametri<a id="parametri" name="parametri"></a></h3> + +<dl> + <dt><code>value</code></dt> + <dd>Il valore da convertire in stringa JSON.</dd> + <dt><code>replacer</code>{{optional_inline}}</dt> + <dd>Una funzione che altera il processo di conversione, o un array di {{jsxref("String")}} e {{jsxref("Number")}} che contiene le proprietà dell'oggetto che devono essere incluse nella stringa JSON. Se il valore è null o non è specificato, tutte le proprietà dell'oggetto sono incluse nel risultato.</dd> + <dt><font face="Consolas, Liberation Mono, Courier, monospace"><code>space</code></font>{{optional_inline}}</dt> + <dd>Un oggetto {{jsxref("String")}} o {{jsxref("Number")}} che viene utilizzato per inserire uno spazio bianco nella stringa JSON di output a fini di leggibilità.Se questo è un <code>Number</code>, indica il numero di caratteri dello spazio da usare come spazio bianco; questo numero è limitato a 10 (se è maggiore, il valore è solo <code>10</code>).Valori inferiori a 1 indicano che non deve essere usato alcuno spazio.</dd> + <dd> + <p>Se si tratta di una <code>String</code>, la stringa (i primi 10 caratteri della stringa, se è più lunga di quella) viene utilizzata come spazio bianco. Se questo parametro non viene fornito (o è {{JSxRef("null")}}), non viene utilizzato alcuno spazio bianco.</p> + + <h3 id="Valore_di_ritorno">Valore di ritorno<a id="Valore_di_Ritorno" name="Valore_di_Ritorno"></a></h3> + + <p>Una stringa JSON che rappresenta il valore dato.</p> + + <h3 id="Eccezioni_2">Eccezioni<a id="Eccezioni" name="Eccezioni"></a></h3> + + <p>Genera un'eccezione {{JSxRef("TypeError")}} ("valore dell'oggetto ciclico") quando viene trovato un riferimento circolare.</p> + </dd> +</dl> + +<h2 id="Descrizione">Descrizione<a id="descrizione" name="descrizione"></a></h2> + +<p><code>JSON.stringify()</code> converte un valore in notazione JSON che lo rappresenta:</p> + +<ul> + <li>Se il valore ha un metodo <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Comportamento_di_toJSON()">toJSON()</a> è responsabile definire quali dati verranno serializzati.</li> + <li>Gli oggetti {{JSxRef("Boolean")}}, {{JSxRef("Number")}}, e {{JSxRef("String")}} vengono convertiti ai corrispondenti valori primitivi durante la stringificazione, in accordo con la semantica di conversione tradizionale.</li> + <li>Se si incontrano {{JSxRef("undefined")}}, una {{JSxRef("Function")}}, o un {{JSxRef("Symbol")}} durante la conversione, viene omesso (quando viene trovato in un oggetto) o viene censurato {{JSxRef("null")}} (quando viene trovato in un array). <code>JSON.stringify()</code> può anche restituire <code>undefined</code> quando si passa in valori "puri" come <code>JSON.stringify(function(){})</code> o <code>JSON.stringify(undefined)</code>.</li> + <li>Tutte le proprietà <a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Symbol" title='The Symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class but is incomplete as a constructor because it does not support the syntax "new Symbol()".'><code>Symbol</code></a>-keyed <font><font>saranno completamente ignorate, anche quando si utilizza la funzione </font></font><code>replacer</code><font><font>.</font></font></li> + <li><font><font>Le istanze di </font></font><a href="https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Date" title="Crea un'istanza Date JavaScript che rappresenta un singolo momento nel tempo. Gli oggetti data sono basati su un valore temporale che è il numero di millisecondi dal 1 ° gennaio 1970 UTC."><code>Date</code></a> <font><font>implementano la funzione </font></font><code>toJSON()</code><font><font> restituendo una stringa (la stessa di </font></font><code>date.toISOString()</code><font><font>). </font><font>Quindi, sono trattati come stringhe.</font></font></li> +</ul> + +<pre class="brush: js">JSON.stringify({}); // '{}' +JSON.stringify(true); // 'true' +JSON.stringify('foo'); // '"foo"' +JSON.stringify([1, 'false', false]); // '[1,"false",false]' +JSON.stringify({ x: 5 }); // '{"x":5}' + +JSON.stringify({ x: 5, y: 6 }); +// '{"x":5,"y":6}' or '{"y":6,"x":5}' +JSON.stringify([new Number(1), new String('false'), new Boolean(false)]); +// '[1,"false",false]' + +// Simboli: +JSON.stringify({ x: undefined, y: Object, z: Symbol('') }); +// '{}' +JSON.stringify({ [Symbol('foo')]: 'foo' }); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]); +// '{}' +JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) { + if (typeof k === 'symbol') { + return 'a symbol'; + } +}); +// '{}' + +// Proprietà non enumerabili: +JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) ); +// '{"y":"y"}' + +</pre> + +<h3 id="Il_parametro_replacer">Il parametro <code>replacer</code></h3> + +<p><font><font>Il parametro </font></font><code>replacer</code><font><font> può essere una funzione o un array.</font></font></p> + +<p><strong><font><font>Come una funzione</font></font></strong><font><font>, prende due parametri: la </font></font><var><font><font>chiave</font></font></var><font><font> e il </font></font><var><font><font>valore che si</font></font></var><font><font> sta stringendo. </font><font>L'oggetto in cui è stata trovata la chiave viene fornito come il parametro </font></font><code>this</code><font><font> </font><font>del replacer.</font></font></p> + +<p><font><font>Inizialmente, la funzione <code>replacer</code> viene chiamata con una stringa vuota come chiave che rappresenta l'oggetto da stringificare. Viene quindi chiamato per ogni proprietà sull'oggetto o sull'array da stringificare.</font></font></p> + +<ul> + <li>Se si restituisce un {{jsxref("Number")}}, la stringa corrispondente a quel numero viene utilizzata come valore per la proprietà quando viene aggiunta alla stringa JSON.</li> + <li>Se si restituisce una {{jsxref("String")}}, tale stringa viene utilizzata come valore della proprietà quando viene aggiunta alla stringa JSON.</li> + <li>Se si restituisce un {{jsxref("Boolean")}}, "true" o "false" viene utilizzato come valore della proprietà, come appropriato, quando viene aggiunto alla stringa JSON.</li> + <li><font><font>Se torni </font></font><code>null</code><font><font>, </font></font><code>null</code> <font><font>verrà aggiunto alla stringa JSON.</font></font></li> + <li>Se si restituisce un qualsiasi altro oggetto, <font><font>l'oggetto viene ricorsivamente stringa nella stringa JSON, chiamando la funzione </font></font><code>replacer</code><font><font> su ogni proprietà, a meno che l'oggetto non sia una funzione, nel qual caso non viene aggiunto nulla alla stringa JSON.</font></font></li> + <li>Se si restituisce <code>undefined</code>, la proprietà non è inclusa (cioè filtrata) nella stringa JSON di output.</li> +</ul> + +<div class="note"><strong>Nota:</strong> N<font><font>on è possibile utilizzare la </font></font><code>replacer</code><font><font>funzione per rimuovere i valori da una matrice. </font><font>Se si restituisce </font></font><code>undefined</code><font><font>o una funzione, </font></font><code>null</code><font><font>viene invece utilizzata.</font></font></div> + +<div class="note">Se desideri che il replacer distingua un oggetto iniziale da una chiave con una proprietà stringa vuota (poiché entrambi fornirebbero la stringa vuota come chiave e potenzialmente un oggetto come valore), sarà necessario tenere traccia del conteggio dell'iterazione (se è al di là della prima iterazione, è una vera e propria chiave di stringa vuota).</div> + +<h4 id="Esempio_di_replacer_come_funzione">Esempio di <em>replacer, </em>come funzione</h4> + +<pre><code>function replacer(key, value) { + // Filtraggio delle proprietà + if (typeof value === 'string') { + return undefined; + } + return value; +} + +var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7}; +JSON.stringify(foo, replacer); +// Risultato: '{"week":45,"month":7}'</code> +</pre> + +<h4 id="Esempio_di_replacer_come_array">Esempio di <em>replacer</em>, come array</h4> + +<p><font><font>Se </font></font><code>replacer</code> <font><font>è un array, i valori dell'array indicano i nomi delle proprietà nell'oggetto che dovrebbero essere incluse nella stringa JSON risultante.</font></font></p> + +<pre class="brush: js">JSON.stringify(foo, ['week', 'month']); +// '{"week":45,"month":7}', mantiene solo le proprietà "week" e "month" +</pre> + +<h3 id="Il_parametro_space">Il parametro <code>space<a id="parametro_space" name="parametro_space"></a></code></h3> + +<p><font><font>L'argomento </font></font><code>space</code><font><font> può essere usato per controllare la spaziatura nella stringa finale.</font></font></p> + +<ul> + <li><strong><font><font>Se si tratta di un numero</font></font></strong><font><font>, i livelli successivi nella stringa verranno rientrati da questi caratteri di spazio (fino a 10).</font></font></li> + <li><strong><font><font>Se è una stringa</font></font></strong><font><font>, i livelli successivi saranno rientrati da questa stringa (o dai primi dieci caratteri di essa).</font></font></li> +</ul> + +<pre><code>JSON.stringify({ a: 2 }, null, ' '); +// '{ +// "a": 2 +// }'</code></pre> + +<p>L'utilizzo di un carattere di tabulazione simula l'aspetto standard di tipo "pretty-print":</p> + +<pre class="brush: js">JSON.stringify({ uno: 1, dos: 2 }, null, '\t'); +// restituisce la stringa: +// '{ +// "uno": 1, +// "dos": 2 +// }' +</pre> + +<h3 id="Comportamento_di_toJSON()">Comportamento di <code>toJSON()</code><a id="comportamento_tojson" name="comportamento_tojson"></a></h3> + +<p><font><font>Se un oggetto da stringificare ha una proprietà denominata il </font></font><code>toJSON</code> <font><font>cui valore è una funzione, il metodo </font></font><code>toJSON()</code> <font><font>personalizza il comportamento di stringificazione JSON: invece dell'oggetto serializzato, il valore restituito dal metodo </font></font><code>toJSON()</code> <font><font>quando chiamato verrà serializzato. </font></font><code>JSON.stringify()</code> <font><font>chiama </font></font><code>toJSON</code> <font><font>con un parametro:</font></font></p> + +<ul> + <li><font><font>se questo oggetto è un valore di proprietà, il nome della proprietà</font></font></li> + <li><font><font>se è in una matrice, l'indice nella matrice, come una stringa</font></font></li> + <li><font><font>una stringa vuota se è </font></font><code>JSON.stringify()</code> <font><font>stata richiamata direttamente su questo oggetto</font></font></li> +</ul> + +<p>Per esempio:</p> + +<pre><code>var obj = { + data: 'data', + + toJSON(key){ + if(key) + return `Ora sono un oggetto nidificato sotto chiave '${key}'`; + + else + return this; + } +}; + +JSON.stringify(obj); +// '{"data":"data"}' + +JSON.stringify({ obj }) +// '{"obj":"Ora sono un oggetto nidificato sotto chiave 'obj'"}' + +JSON.stringify([ obj ]) +// '["Ora sono un oggetto nidificato sotto chiave '0'"]'</code> +</pre> + +<h3 id="Problema_con_JSON.stringify()_durante_la_serializzazione_di_riferimenti_circolari">Problema con <code>JSON.stringify()</code> durante la serializzazione di riferimenti circolari</h3> + +<p>Nota che poiché il <a href="https://www.json.org/">Formato JSON</a> non supporta i riferimenti agli oggetti (sebbene <a href="http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03">esista una bozza IETF</a>), {{JSxRef("TypeError")}} verrà generato un se si tenta di codificare un oggetto con riferimenti circolari.</p> + +<pre class="brush: js example-bad">const circularReference = {}; +circularReference.myself = circularReference; + +// La serializzazione dei riferimenti circolari genera "TypeError: valore dell'oggetto ciclico" +JSON.stringify(circularReference); +</pre> + +<p>Per serializzare i riferimenti circolari è possibile utilizzare una libreria che li supporta (ad es. <a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> di Douglas Crockford) o implementare una soluzione autonomamente, che richiederà la ricerca e la sostituzione (o la rimozione) dei riferimenti ciclici mediante valori serializzabili.</p> + +<h3 id="Problema_con_plain_JSON.stringify_per_l'uso_come_JavaScript"><font><font>Problema con plain </font></font> <code>JSON.stringify</code> per l'uso come JavaScript</h3> + +<p>Storicamente, JSON <a href="http://timelessrepo.com/json-isnt-a-javascript-subset">non era un sottoinsieme completamente rigido di JavaScript</a>. <font>I punti del codice letterale U + 2028 LINE SEPARATOR e U + 2029 PARAGRAPH SEPARATOR potrebbero apparire letteralmente in stringhe letterali e nomi di proprietà nel testo JSON. </font><font>Ma non potevano apparire letteralmente in un contesto simile nel testo JavaScript - solo usando escape Unicode come</font> <code>\u2028</code> e <code>\u2029</code>. Questo è cambiato di recente: ora entrambi i punti di codice possono apparire letteralmente nelle stringhe in JSON e JavaScript entrambi.</p> + +<p><font><font>Pertanto, se è richiesta la compatibilità con i motori JavaScript precedenti, è pericoloso sostituire direttamente la stringa restituita da </font></font><code>JSON.stringify</code> <font><font>una stringa JavaScript da passare a </font></font><code>eval</code> <font><font>o </font></font><code>new Function</code> <font><font>o come parte di un </font><font>URL </font></font><a href="https://en.wikipedia.org/wiki/JSONP" rel="noopener"><font><font>JSONP</font></font></a><font><font> e può essere utilizzata la seguente utility:</font></font></p> + +<pre class="brush: js">function jsFriendlyJSONStringify (s) { + return JSON.stringify(s). + replace(/\u2028/g, '\\u2028'). + replace(/\u2029/g, '\\u2029'); +} + +var s = { + a: String.fromCharCode(0x2028), + b: String.fromCharCode(0x2029) +}; +try { + eval('(' + JSON.stringify(s) + ')'); +} catch (e) { + console.log(e); // "SyntaxError: unterminated string literal" +} + +// No need for a catch +eval('(' + jsFriendlyJSONStringify(s) + ')'); + +// console.log in Firefox scolla l'Unicode se +// connesso alla console, quindi usiamo alert +alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"} +</pre> + +<div class="blockIndicator note"> +<p><strong>Note</strong>: N<font>on è garantito che le proprietà degli oggetti non array vengano sottoposte a stringa in qualsiasi ordine particolare. </font><font>Non fare affidamento sull'ordinamento di proprietà all'interno dello stesso oggetto all'interno della stringa.</font></p> +</div> + +<pre class="brush: js">var a = JSON.stringify({ foo: "bar", baz: "quux" }) +//'{"foo":"bar","baz":"quux"}' +var b = JSON.stringify({ baz: "quux", foo: "bar" }) +//'{"baz":"quux","foo":"bar"}' +console.log(a !== b) // true + +// alcune funzioni di memoizzazione usano JSON.stringify per serializzare gli argomenti, +// mancando la cache quando si incontra lo stesso oggetto come sopra +</pre> + +<h3 id="Esempio_di_utilizzo_JSON.stringify()_con_localStorage">Esempio di utilizzo <code>JSON.stringify()</code> con <code>localStorage</code></h3> + +<p><font><font>Nel caso in cui desideri archiviare un oggetto creato dall'utente e consentirne il ripristino anche dopo la chiusura del browser, nell'esempio seguente è disponibile un modello per l'applicabilità di </font></font><code>JSON.stringify()</code><font><font>:</font></font></p> + +<pre class="brush: js">// Creare un esempio di JSON +var session = { + 'screens': [], + 'state': true +}; +session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 }); +session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 }); +session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 }); +session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 }); +session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 }); +session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 }); + +// Conversione della stringa JSON con JSON.stringify() +// quindi salva con localStorage nel nome della sessione +localStorage.setItem('session', JSON.stringify(session)); + +// Esempio di come trasformare la stringa generata tramite +// JSON.stringify() e salvare nuovamente in localStorage nell'oggetto JSON +var restoredSession = JSON.parse(localStorage.getItem('session')); + +// Ora la variabile restoreSession contiene l'oggetto che è stato salvato +// in localStorage +console.log(restoredSession); +</pre> + +<h3 id="Well-formed_JSON.stringify()">Well-formed <code>JSON.stringify()</code></h3> + +<p>Engines implementing the <a href="https://github.com/tc39/proposal-well-formed-stringify">well-formed JSON.stringify specification</a> will stringify lone surrogates -- any code point from U+D800 to U+DFFF -- using Unicode escape sequences rather than literally. Before this change <code>JSON.stringify</code> would output lone surrogates if the input contained any lone surrogates; such strings could not be encoded in valid UTF-8 or UTF-16:</p> + +<pre class="brush: js; no-line-numbers">JSON.stringify("\uD800"); // '"�"'</pre> + +<p><font><font>Ma con questo cambiamento </font></font><code>JSON.stringify</code> <font><font>rappresentano surrogati solitari usando sequenze di escape JSON che </font></font><em><font><font>possono</font></font></em><font><font> essere codificate in UTF-8 o UTF-16 validi:</font></font></p> + +<pre class="brush: js; no-line-numbers">JSON.stringify("\uD800"); // '"\\ud800"'</pre> + +<p><font><font>Questo cambiamento dovrebbe essere retrocompatibile fin tanto che si passa il risultato di </font></font><code>JSON.stringify</code> <font><font>API come </font></font><code>JSON.parse</code> <font><font>quella che accetterà qualsiasi testo JSON valido, in quanto tratterà le escape Unicode dei surrogati soli come identici ai surrogati solitari stessi. </font></font><em><font><font>Solo</font></font></em><font><font> se stai interpretando direttamente il risultato di </font></font><code>JSON.stringify</code> <font><font>hai bisogno di gestire attentamente </font></font><code>JSON.stringify</code> <font><font>le due possibili codifiche di questi punti di codice.</font></font></p> + +<h2 id="Specifiche">Specifiche</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specifica</th> + <th scope="col">Stato</th> + <th scope="col">Commento</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definzione iniziale. Implementato su JavaScript 1.7.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatiblità_con_i_browser">Compatiblità con i browser</h2> + +<div> + + +<p>{{Compat("javascript.builtins.JSON.stringify")}}</p> +</div> + +<h2 id="Vedi_anche">Vedi anche</h2> + +<ul> + <li>{{JSxRef("JSON.parse()")}}</li> + <li><a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">cycle.js</a> – Presenta due funzioni: <code>JSON.decycle</code> e <code>JSON.retrocycle</code>. Esse consentono la codifica e la decodifica di strutture cicliche e DAG in un formato JSON esteso e retrocompatibile.</li> +</ul> |