Lavorare con JSON

Questa traduzione è incompleta. Aiutaci a tradurre questo articolo dall’inglese

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.

Prerequisiti: Conoscenza informatica di base, comprensione base di HTML e CSS, familiarità con i concetti base di JavaScript (vedi Primi passi e Costruzione blocchi) e con i concetti base degli oggetti JS (vedi Introduzione agli oggetti).
Obiettivi: Comprendere il funzionamento dei dati megorizzati in JSON e creare i tuoi oggetti JSON.

No, davvero, cos'è JSON?

JSON è un formato dati testuale che segue la sintassi degli oggetti JavaScript, reso popolare da Douglas Crockford. 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.

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 JSON di JavaScript.

Nota: Convertire una stringa in un oggetto nativo è chiamata deserializzazione, mentre convertire un oggetto nativo in una stringa in modo da poterlo trasmettere in rete, è chiamata serializzazione.

Un oggetto JSON object può essere memorizzato in un file dedicato, essenzialmente un file di testo con estensione .json, e un tipo MIME application/json.

Struutura di un JSON 

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:

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

Se carichiamo questo oggetto in un programma, processato in una variabile chiamata superHeroes per esempio, potremmo accedere ai dati che contiene usando la medesima notazione punto/parentesi vista nell'articolo Fondamentali degli oggetti JavaScript. Per esempio:

superHeroes.homeTown
superHeroes['active']

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:

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

Note: Abbiamo reso disponibile il JSON visto sopra, in una variabile del nostro esempio JSONTest.html (vedi il codice sorgente). Prova a caricarlo e poi accedi alla variabile dalla console JavaScript del tuo browser.

Arrays as JSON

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:

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

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 [0]["powers"][0].

Other notes

  • JSON is purely a data format — it contains only properties, no methods.
  • JSON requires double quotes to be used around strings and property names. Single quotes are not valid.
  • 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 JSONLint.
  • 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.
  • Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Active learning: Working through a JSON example

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

Getting started

To begin with, make local copies of our heroes.html and style.css files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML:

<header>
</header>

<section>
</section>

Plus a <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 <header> and <section> elements and store them in variables:

const header = document.querySelector('header');
const section = document.querySelector('section');

We have made our JSON data available on our GitHub, at https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.

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

Obtaining the JSON

To obtain the JSON, we use an API called XMLHttpRequest (often called XHR). 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.

  1. 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:
    let requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  2. To create a request, we need to create a new request object instance from the XMLHttpRequest constructor, using the new keyword. Add the following below your last line:
    let request = new XMLHttpRequest();
  3. Now we need to open the request using the open() method. Add the following line:
    request.open('GET', requestURL);

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

    • The HTTP method to use when making the network request. In this case GET is fine, as we are just retrieving some simple data.
    • The URL to make the request to — this is the URL of the JSON file that we stored earlier.
  4. Next, add the following two lines — here we are setting the responseType 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 send() method:
    request.responseType = 'json';
    request.send();
  5. 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:
    request.onload = function() {
      const superHeroes = request.response;
      populateHeader(superHeroes);
      showHeroes(superHeroes);
    }

Here we are storing the response to our request (available in the response property) in a variable called superHeroes; 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 <header> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <section>.

We have wrapped the code in an event handler that runs when the load event fires on the request object (see onload) — this is because the load event fires when the response has successfully returned; doing it this way guarantees that request.response will definitely be available when we come to try to do something with it.

Populating the header

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:

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);
}

We named the parameter jsonObj, to remind ourselves that this JavaScript object originated from JSON. Here we first create an <h1> element with createElement(), set its textContent to equal the squadName property of the object, then append it to the header using appendChild(). 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 homeTown and formed properties of the object.

Creating the hero information cards

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

function showHeroes(jsonObj) {
  const heroes = jsonObj['members'];
      
  for (let i = 0; i < 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 < 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);
  }
}

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

Next, we use a for loop to loop through each object in the array. For each one, we:

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

Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)

Note: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json 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 JavaScript object basics article for more information on dot and bracket notation.

Converting between objects and text

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:

request.responseType = 'json';

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 JSON object is available in browsers, which contains the following two methods:

  • parse(): Accepts a JSON string as a parameter, and returns the corresponding JavaScript object.
  • stringify(): Accepts an object as a parameter, and returns the equivalent JSON string form.

You can see the first one in action in our heroes-finished-json-parse.html example (see the source code) — 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 parse() to convert it to an actual JavaScript object. The key snippet of code is here:

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);
}

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

let myJSON = { "name": "Chris", "age": "38" };
myJSON
let myString = JSON.stringify(myJSON);
myString

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

Test your skills!

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 Test your skills: JSON.

Summary

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.

See also

In this module