aboutsummaryrefslogtreecommitdiff
path: root/files/it/learn/javascript/oggetti/json/index.html
blob: 71cf166e159cd8a806afecc1cc753092ab6769b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
---
title: Lavorare con JSON
slug: Learn/JavaScript/Oggetti/JSON
translation_of: Learn/JavaScript/Objects/JSON
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</div>

<p class="summary">JavaScript Object Notation (JSON) è un formato testuale standard, usato per rappresentare dati strutturati basati sulla sintassi degli oggetti in JavaScript. E' usato comunemente per la trasmissione dati nelle applicazioni web (ad es. inviare dati dal server al client in modo da visualizzarli in una pagina web o viceversa). Ti imbatterai abbastanza spesso in questo formato, così in questo articolo ti forniremo tutto ciò che ti occorre per lavorare con JSON usando JavaScript, incluso la lettura (parsing) del JSON in modo da accedere ai dati in esso contenuti, così come a generare JSON.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisiti:</th>
   <td>Conoscenza informatica di base, comprensione base di HTML e CSS, familiarità con i concetti base di JavaScript (vedi <a href="/en-US/docs/Learn/JavaScript/First_steps">Primi passi</a> e <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Costruzione blocchi</a>) e con i concetti base degli oggetti JS (vedi <a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduzione agli oggetti</a>).</td>
  </tr>
  <tr>
   <th scope="row">Obiettivi:</th>
   <td>Comprendere il funzionamento dei dati megorizzati in JSON e creare i tuoi oggetti JSON.</td>
  </tr>
 </tbody>
</table>

<h2 id="No_davvero_cosè_JSON">No, davvero, cos'è JSON?</h2>

<p>{{glossary("JSON")}} è un formato dati testuale che segue la sintassi degli oggetti JavaScript, reso popolare da <a href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>. Anche se richiama da vicino la sintassi letterale degli oggetti JavaScript, può essere usato indipendentemente da JavaScript, e molti ambienti di programmazione supportano la lettura (parsing) e la generazione di JSON.</p>

<p>JSON esiste sotto forma di una stringa — utile quando vuoi trasmettere dati in una rete. Deve essere poi convertito in un oggetto javaScript nativo quando vuoi accedere ai dati che rappresenta. La conversione tra i due è piuttosto banale —  grazie ai metodi dell'oggetto globale <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> di JavaScript.</p>

<div class="note">
<p><strong>Nota</strong>: Convertire una stringa in un oggetto nativo è chiamata <em>deserializzazione</em>, mentre convertire un oggetto nativo in una stringa in modo da poterlo trasmettere in rete, è chiamata <em>serializzazione</em>.</p>
</div>

<p>Un oggetto JSON object può essere memorizzato in un file dedicato, essenzialmente un file di testo con estensione <code>.json</code>, e un {{glossary("tipo MIME")}} <code>application/json</code>.</p>

<h3 id="Struutura_di_un_JSON">Struutura di un JSON </h3>

<p>Come descritto sopra, un JSON non è altro che una stringa il cui formato è molto simile al formato letterale di un oggetto JavaScript. E' possibile includere in JSON gli stessi tipi di dato base possibili in un oggetto standard di JavaScript — stringhe, numeri, arrays, booleani e altri oggetti letterali. Questo ti consente di costruire una gerarchia dei dati, ad esempio:</p>

<pre class="brush: json">{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}</pre>

<p>Se carichiamo questo oggetto in un programma, processato in una variabile chiamata <code>superHeroes</code> per esempio, potremmo accedere ai dati che contiene usando la medesima notazione punto/parentesi vista nell'articolo <a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Fondamentali degli oggetti JavaScript</a>. Per esempio:</p>

<pre class="brush: js">superHeroes.homeTown
superHeroes['active']</pre>

<p>Per accedere ai dati gerarchicamente inferiori, occorre semplicemente concatenare i nome delle proprietà e gli indici degli array.  Ad esempio, per accedere al terzo superpotere del secondo eroe nella lista dei membri, procedi come segue:</p>

<pre class="brush: js">superHeroes['members'][1]['powers'][2]</pre>

<ol>
 <li>Per primo abbiamo il nome della variabile — <code>superHeroes</code>.</li>
 <li>All'interno della variabile vogliamo accedere alla proprietà <code>members</code>, così utilizziamo <code>["members"]</code>.</li>
 <li><code>members</code> contiene un array popolato da oggetti. Noi vogliamo accedere al secondo oggetto dell'array, quindi usiamo <code>[1]</code>.</li>
 <li>all'interno dell'oggetto così trovato, vogliamo poi accedere alla proprietà <code>powers</code> e per ciò usiamo <code>["powers"]</code>.</li>
 <li>La proprietà <code>powers</code> contiene a sua volta un array in cui sono elencate i superpoteri dell'eroe selezionato. Noi vogliamo la terza in lista, usiamo quindi <code>[2]</code>.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: Abbiamo reso disponibile il JSON visto sopra, in una variabile del nostro esempio <a href="http://mdn.github.io/learning-area/javascript/oojs/json/JSONTest.html">JSONTest.html</a> (vedi il <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/JSONTest.html">codice sorgente</a>). Prova a caricarlo e poi accedi alla variabile dalla console JavaScript del tuo browser.</p>
</div>

<h3 id="Arrays_as_JSON">Arrays as JSON</h3>

<p>Above we mentioned that JSON text basically looks like a JavaScript object, and this is mostly right. The reason we said "mostly right" is that an array is also valid JSON, for example:</p>

<pre class="brush: json">[
  {
    "name": "Molecule Man",
    "age": 29,
    "secretIdentity": "Dan Jukes",
    "powers": [
      "Radiation resistance",
      "Turning tiny",
      "Radiation blast"
    ]
  },
  {
    "name": "Madame Uppercut",
    "age": 39,
    "secretIdentity": "Jane Wilson",
    "powers": [
      "Million tonne punch",
      "Damage resistance",
      "Superhuman reflexes"
    ]
  }
]</pre>

<p>The above is perfectly valid JSON. You'd just have to access array items (in its parsed version) by starting with an array index, for example <code>[0]["powers"][0]</code>.</p>

<h3 id="Other_notes">Other notes</h3>

<ul>
 <li>JSON is purely a data format — it contains only properties, no methods.</li>
 <li>JSON requires double quotes to be used around strings and property names. Single quotes are not valid.</li>
 <li>Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like <a href="http://jsonlint.com/">JSONLint</a>.</li>
 <li>JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be a valid JSON object.</li>
 <li>Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.</li>
</ul>

<h2 id="Active_learning_Working_through_a_JSON_example">Active learning: Working through a JSON example</h2>

<p>So, let's work through an example to show how we could make use of some JSON data on a website.</p>

<h3 id="Getting_started">Getting started</h3>

<p>To begin with, make local copies of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes.html">heroes.html</a> and <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/style.css">style.css</a> files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML:</p>

<pre class="brush: html">&lt;header&gt;
&lt;/header&gt;

&lt;section&gt;
&lt;/section&gt;</pre>

<p>Plus a {{HTMLElement("script")}} element to contain the JavaScript code we will be writing in this exercise. At the moment it only contains two lines, which grab references to the {{HTMLElement("header")}} and {{HTMLElement("section")}} elements and store them in variables:</p>

<pre class="brush: js">const header = document.querySelector('header');
const section = document.querySelector('section');</pre>

<p>We have made our JSON data available on our GitHub, at <a href="https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json</a>.</p>

<p>We are going to load it into our page, and use some nifty DOM manipulation to display it, like this:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/13857/json-superheroes.png" style="display: block; margin: 0 auto;"></p>

<h3 id="Obtaining_the_JSON">Obtaining the JSON</h3>

<p>To obtain the JSON, we use an API called {{domxref("XMLHttpRequest")}} (often called <strong>XHR</strong>). This is a very useful JavaScript object that allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page. This has led to more responsive web pages, and sounds exciting, but it is beyond the scope of this article to teach it in much more detail.</p>

<ol>
 <li>To start with, we store the URL of the JSON we want to retrieve in a variable. Add the following at the bottom of your JavaScript code:
  <pre class="brush: js">let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';</pre>
 </li>
 <li>To create a request, we need to create a new request object instance from the <code>XMLHttpRequest</code> constructor, using the <code>new</code> keyword. Add the following below your last line:
  <pre class="brush: js">let request = new XMLHttpRequest();</pre>
 </li>
 <li>Now we need to open the request using the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/open">open()</a></code> method. Add the following line:
  <pre class="brush: js">request.open('GET', requestURL);</pre>

  <p>This takes at least two parameters — there are other optional parameters available. We only need the two mandatory ones for this simple example:</p>

  <ul>
   <li>The HTTP method to use when making the network request. In this case <code><a href="/en-US/docs/Web/HTTP/Methods/GET">GET</a></code> is fine, as we are just retrieving some simple data.</li>
   <li>The URL to make the request to — this is the URL of the JSON file that we stored earlier.</li>
  </ul>
 </li>
 <li>Next, add the following two lines — here we are setting the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/responseType">responseType</a></code> to JSON, so that XHR knows that the server will be returning JSON, and that this should be converted behind the scenes into a JavaScript object. Then we send the request with the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/send">send()</a></code> method:
  <pre class="brush: js">request.responseType = 'json';
request.send();</pre>
 </li>
 <li>The last bit of this section involves waiting for the response to return from the server, then dealing with it. Add the following code below your previous code:
  <pre class="brush: js">request.onload = function() {
  const superHeroes = request.response;
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}</pre>
 </li>
</ol>

<p>Here we are storing the response to our request (available in the <code><a href="/en-US/docs/Web/API/XMLHttpRequest/response">response</a></code> property) in a variable called <code>superHeroes</code>; this variable now contains the JavaScript object based on the JSON! We are then passing that object to two function calls — the first one fills the &lt;<code>header&gt;</code> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <code>&lt;section&gt;</code>.</p>

<p>We have wrapped the code in an event handler that runs when the load event fires on the request object (see <code><a href="/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload">onload</a></code>) — this is because the load event fires when the response has successfully returned; doing it this way guarantees that <code>request.response</code> will definitely be available when we come to try to do something with it.</p>

<h3 id="Populating_the_header">Populating the header</h3>

<p>Now that we've retrieved the JSON data and converted it into a JavaScript object, let's make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:</p>

<pre class="brush: js">function populateHeader(jsonObj) {
  const myH1 = document.createElement('h1');
  myH1.textContent = jsonObj['squadName'];
  header.appendChild(myH1);

  const myPara = document.createElement('p');
  myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
  header.appendChild(myPara);
}</pre>

<p>We named the parameter <code>jsonObj</code>, to remind ourselves that this JavaScript object originated from JSON. Here we first create an {{HTMLElement("h1")}} element with <code><a href="/en-US/docs/Web/API/Document/createElement">createElement()</a></code>, set its <code><a href="/en-US/docs/Web/API/Node/textContent">textContent</a></code> to equal the <code>squadName</code> property of the object, then append it to the header using <code><a href="/en-US/docs/Web/API/Node/appendChild">appendChild()</a></code>. We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a concatenated string containing both the <code>homeTown</code> and <code>formed</code> properties of the object.</p>

<h3 id="Creating_the_hero_information_cards">Creating the hero information cards</h3>

<p>Next, add the following function at the bottom of the code, which creates and displays the superhero cards:</p>

<pre class="brush: js">function showHeroes(jsonObj) {
  const heroes = jsonObj['members'];

  for (let i = 0; i &lt; heroes.length; i++) {
    const myArticle = document.createElement('article');
    const myH2 = document.createElement('h2');
    const myPara1 = document.createElement('p');
    const myPara2 = document.createElement('p');
    const myPara3 = document.createElement('p');
    const myList = document.createElement('ul');

    myH2.textContent = heroes[i].name;
    myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
    myPara2.textContent = 'Age: ' + heroes[i].age;
    myPara3.textContent = 'Superpowers:';

    const superPowers = heroes[i].powers;
    for (let j = 0; j &lt; superPowers.length; j++) {
      const listItem = document.createElement('li');
      listItem.textContent = superPowers[j];
      myList.appendChild(listItem);
    }

    myArticle.appendChild(myH2);
    myArticle.appendChild(myPara1);
    myArticle.appendChild(myPara2);
    myArticle.appendChild(myPara3);
    myArticle.appendChild(myList);

    section.appendChild(myArticle);
  }
}</pre>

<p>To start with, we store the <code>members</code> property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.</p>

<p>Next, we use a <a href="/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#The_standard_for_loop">for loop</a> to loop through each object in the array. For each one, we:</p>

<ol>
 <li>Create several new elements: an <code>&lt;article&gt;</code>, an <code>&lt;h2&gt;</code>, three <code>&lt;p&gt;</code>s, and a <code>&lt;ul&gt;</code>.</li>
 <li>Set the <code>&lt;h2&gt;</code> to contain the current hero's <code>name</code>.</li>
 <li>Fill the three paragraphs with their <code>secretIdentity</code>, <code>age</code>, and a line saying "Superpowers:" to introduce the information in the list.</li>
 <li>Store the <code>powers</code> property in another new constant called <code>superPowers</code> — this contains an array that lists the current hero's superpowers.</li>
 <li>Use another <code>for</code> loop to loop through the current hero's superpowers — for each one we create an <code>&lt;li&gt;</code> element, put the superpower inside it, then put the <code>listItem</code> inside the <code>&lt;ul&gt;</code> element (<code>myList</code>) using <code>appendChild()</code>.</li>
 <li>The very last thing we do is to append the <code>&lt;h2&gt;</code>, <code>&lt;p&gt;</code>s, and <code>&lt;ul&gt;</code> inside the <code>&lt;article&gt;</code> (<code>myArticle</code>), then append the <code>&lt;article&gt;</code> inside the <code>&lt;section&gt;</code>. The order in which things are appended is important, as this is the order they will be displayed inside the HTML.</li>
</ol>

<div class="note">
<p><strong>Note</strong>: If you are having trouble getting the example to work, try referring to our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished.html">heroes-finished.html</a> source code (see it <a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished.html">running live</a> also.)</p>
</div>

<div class="note">
<p><strong>Note</strong>: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the <a href="http://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json">superheroes.json</a> file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our <a href="/en-US/docs/Learn/JavaScript/Objects/Basics">JavaScript object basics</a> article for more information on dot and bracket notation.</p>
</div>

<h2 id="Converting_between_objects_and_text">Converting between objects and text</h2>

<p>The above example was simple in terms of accessing the JavaScript object, because we set the XHR request to convert the JSON response directly into a JavaScript object using:</p>

<pre class="brush: js">request.responseType = 'json';</pre>

<p>But sometimes we aren't so lucky — sometimes we receive a raw JSON string, and we need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we need to convert it to JSON (a string) before sending. Luckily, these two problems are so common in web development that a built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON</a> object is available in browsers, which contains the following two methods:</p>

<ul>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">parse()</a></code>: Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.</li>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringify()</a></code>: Accepts an object as a parameter, and returns the equivalent JSON string form.</li>
</ul>

<p>You can see the first one in action in our <a href="http://mdn.github.io/learning-area/javascript/oojs/json/heroes-finished-json-parse.html">heroes-finished-json-parse.html</a> example (see the <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/json/heroes-finished-json-parse.html">source code</a>) — this does exactly the same thing as the example we built up earlier, except that we set the XHR to return the raw JSON text, then used <code>parse()</code> to convert it to an actual JavaScript object. The key snippet of code is here:</p>

<pre class="brush: js">request.open('GET', requestURL);
request.responseType = 'text'; // now we're getting a string!
request.send();

request.onload = function() {
  const superHeroesText = request.response; // get the string from the response
  const superHeroes = JSON.parse(superHeroesText); // convert it to an object
  populateHeader(superHeroes);
  showHeroes(superHeroes);
}</pre>

<p>As you might guess, <code>stringify()</code> works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:</p>

<pre class="brush: js">let myJSON = { "name": "Chris", "age": "38" };
myJSON
let myString = JSON.stringify(myJSON);
myString</pre>

<p>Here we're creating a JavaScript object, then checking what it contains, then converting it to a JSON string using <code>stringify()</code> — saving the return value in a new variable — then checking it again.</p>

<h2 id="Test_your_skills!">Test your skills!</h2>

<p>You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see <a href="/en-US/docs/Learn/JavaScript/Objects/Test_your_skills:_JSON">Test your skills: JSON</a>.</p>

<h2 id="Summary">Summary</h2>

<p>In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON">JSON object reference page</a></li>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest object reference page</a></li>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li>
 <li><a href="/en-US/docs/Web/HTTP/Methods">HTTP request methods</a></li>
 <li><a href="http://json.org">Official JSON web site with link to ECMA standard</a></li>
</ul>

<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}</p>

<h2 id="In_this_module">In this module</h2>

<ul>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Object basics</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">Inheritance in JavaScript</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_building_practice">Object building practice</a></li>
 <li><a href="/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Adding features to our bouncing balls demo</a></li>
</ul>