×

注意!页面内容来自https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/JSON,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

Working with JSON

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g.sending some data from the server to the clientso it can be displayed on a web pageor vice versa). You'll come across it quite oftenso in this articlewe give you all you need to work with JSON using JavaScriptincluding parsing JSON so you can access data within itand creating JSON.

Prerequisites: An understanding of HTML and the fundamentals of CSSfamiliarity with JavaScript basics as covered in previous lessons.
Learning outcomes:
  • What JSON is — a very commonly used data format based on JavaScript object syntax.
  • That JSON can also contain arrays.
  • Retrieve JSON as a JavaScript object using mechanisms available in Web APIs (for exampleResponse.on() in the Fetch API).
  • Access values inside JSON data using bracket and dot syntax.
  • Converting between objects and text using JSON.parse() and JSON.stringify().

Noreallywhat is JSON?

JSON is a text-based data format following JavaScript object syntax. It represents structured data as a stringwhich is useful when you want to transmit data across a network. Even though it closely resembles JavaScript object literal syntaxit can be used independently from JavaScript. Many programming environments feature the ability to read (parse) and generate JSON. In JavaScriptthe methods for parsing and generating JSON are provided by the JSON object.

Note: Converting a string to a native object is called deserializationwhile converting a native object to a string so it can be transmitted across the network is called serialization.

A JSON string can be stored in its own filewhich is basically just a text file with an extension of .onand a MIME type of application/on.

JSON structure

As described aboveJSON is a string whose format very much resembles JavaScript object literal format. The following is a valid JSON string representing an object. Note that it is also a valid JavaScript object literal — just with some more syntax restrictions.

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

If you load this JSON in your JavaScript program as a stringyou can parse it into a normal object and then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article. For example:

superHeroes.homeTown;
superHeroes.members[1].powers[2];
  1. Firstwe have the variable name — superHeroes.
  2. Inside thatwe want to access the members propertyso we use .members.
  3. members contains an array populated by objects. We want to access the second object inside the arrayso we use [1].
  4. Inside this objectwe want to access the powers propertyso we use .powers.
  5. Inside the powers property is an array containing the selected hero's superpowers. We want the third oneso we use [2].

The key takeaway is that there's really nothing special about working with JSON; after you've parsed it into a JavaScript objectyou work with it just like you would with an object declared using the same object literal syntax.

Note: We've made the JSON seen above available inside a variable in our JSONTest.html example (see the source code). Try loading this up and then accessing data inside the variable via your browser's JavaScript console.

Arrays as JSON

Above we mentioned that JSON text basically looks like a JavaScript object inside a string. We can also convert arrays to/from JSON. The below example is perfectly valid JSON:

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

You have to access array items (in its parsed version) by starting with an array indexfor example superHeroes[0].powers[0].

The JSON can also contain a single primitive. For example29"Dan Jukes"or true are all valid JSON.

JSON syntax restrictions

As mentioned earlierany JSON is a valid JavaScript literal (objectarraynumberetc.). The converse is not truethough—not all JavaScript object literals are valid JSON.

  • JSON can only contain serializable data types. This means:
    • For primitivesJSON can contain string literalsnumber literalstruefalseand null. Notablyit cannot contain undefinedNaNor Infinity.
    • For non-primitivesJSON can contain object literals and arraysbut not functions or any other object typessuch as DateSetand Map. The objects and arrays inside JSON need to further contain valid JSON data types.
  • Strings must be enclosed in double quotesnot single quotes.
  • Numbers must be written in decimal notation.
  • Each property of an object must be in the form of "key": value. Property names must be string literals enclosed in double quotes. Special JavaScript syntaxsuch as methodsis not allowed because methods are functionsand functions are not valid JSON data types.
  • Objects and arrays cannot contain trailing commas.
  • Comments are not allowed in JSON.

Even a single misplaced comma or colon can make a JSON file invalid and cause it to fail. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errorsas long as the generator program is working correctly). You can validate JSON using an application like JSONLint or JSON-validate

Note: Now you've read through this sectionyou might also want to supplement your learning with Scrimba's JSON review MDN learning partner interactive tutorialwhich provides some useful guidance around basic JSON syntax and how to view JSON request data inside your browser's devtools.

Working through a JSON example

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

Getting started

To begin withmake local copies of our heroes.html and .css files. The latter contains some simple CSS to our pagewhile the former contains some very simple body HTMLplus a <script> element to contain the JavaScript code we will be writing in this exercise:

html
<header>
...
</header>

<section>
...
</section>

<script>
// JavaScript goes here
</script>

We have made our JSON data available on our GitHubat https://mdn.github.io/learning-area/javascript/oo/on/superheroes.on.

We are going to load the JSON into our scriptand use some nifty DOM manipulation to display itlike this:

Image of a document titled "Super hero squad" (in a fancy font) and subtitled "Hometown: Metro City // Formed: 2016". Three columns below the heading are titled "Molecule Man""Madame Uppercut"and "Eternal Flame"respectively. Each column lists the hero's secret identity nameageand superpowers.

Top-level function

The top-level function looks like this:

async function populate() {
  const requestURL =
    "https://mdn.github.io/learning-area/javascript/oo/on/superheroes.on";
  const request = new Request(requestURL);

  const response = await fetch(request);
  const superHeroes = await response.on();

  populateHeader(superHeroes);
  populateHeroes(superHeroes);
}

To obtain the JSONwe use an API called Fetch. This API allows us to make network requests to retrieve resources from a server via JavaScript (e.g.imagestextJSONeven HTML snippets)meaning that we can update small sections of content without having to reload the entire page.

In our functionthe first four lines use the Fetch API to fetch the JSON from the server:

  • we declare the requestURL variable to store the GitHub URL
  • we use the URL to initialize a new Request object.
  • we make the network request using the fetch() functionand this returns a Response object
  • we retrieve the response as JSON using the on() function of the Response object.

Note: The fetch() API is asynchronous. You can learn about asynchronous functions in detail in our Asynchronous JavaScript modulebut for nowwe'll just say that we need to add the keyword async before the name of the function that uses the fetch APIand add the keyword await before the calls to any asynchronous functions.

After all thatthe superHeroes variable will contain 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 datawhile the second one creates an information card for each hero on the teamand inserts it into the <section>.

Populating the header

Now that we've retrieved the JSON data and converted it into a JavaScript objectlet's make use of it by writing the two functions we referenced above. First of alladd the following function definition below the previous code:

function populateHeader(obj) {
  const header = document.querySelector("header");
  const myH1 = document.createElement("h1");
  myH1.textContent = obj.squadName;
  header.appendChild(myH1);

  const myPara = document.createElement("p");
  myPara.textContent = `Hometown: ${obj.homeTown} // Formed: ${obj.formed}`;
  header.appendChild(myPara);
}

Here we first create an h1 element with createElement()set its textContent to equal the squadName property of the objectthen append it to the header using appendChild(). We then do a very similar operation with a paragraph: create itset its text content and append it to the header. The only difference is that its text is set to a template literal containing both the homeTown and formed properties of the object.

Creating the hero information cards

Nextadd the following function at the bottom of the codewhich creates and displays the superhero cards:

function populateHeroes(obj) {
  const section = document.querySelector("section");
  const heroes = obj.members;

  for (const hero of heroes) {
    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 = hero.name;
    myPara1.textContent = `Secret identity: ${hero.secretIdentity}`;
    myPara2.textContent = `Age: ${hero.age}`;
    myPara3.textContent = "Superpowers:";

    const superPowers = hero.powers;
    for (const power of superPowers) {
      const listItem = document.createElement("li");
      listItem.textContent = power;
      myList.appendChild(listItem);
    }

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

    section.appendChild(myArticle);
  }
}

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

Nextwe use a for...of loop to iterate through each object in the array. For each onewe:

  1. Create several new elements: an <article>an <h2>three <p>sand a <ul>.
  2. Set the <h2> to contain the current hero's name.
  3. Fill the three paragraphs with their secretIdentityageand 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...of loop to loop through the current hero's superpowers — for each one we create an <li> elementput the superpower inside itthen put the listItem inside the <ul> element (myList) using appendChild().
  6. The very last thing we do is to append the <h2><p>sand <ul> inside the <article> (myArticle)then append the <article> inside the <section>. The order in which things are appended is importantas this is the order they will be displayed inside the HTML.

Note: If you are having trouble getting the example to worktry 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 objectit can help to have the superheroes.on file open in another tab or your text editorand 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.

Calling the top-level function

Finallywe need to call our top-level populate() function:

populate();

Converting between objects and text

The above example was simple in terms of accessing the JavaScript objectbecause we converted the network response directly into a JavaScript object using response.on().

But sometimes we aren't so lucky — sometimes we receive a raw JSON stringand we need to convert it to an object ourselves. And when we want to send a JavaScript object across the networkwe need to convert it to JSON (a string) before sending it. Luckilythese two problems are so common in web development that a built-in JSON object is available in browserswhich contains the following two methods:

  • parse(): Accepts a JSON string as a parameterand returns the corresponding JavaScript object.
  • stringify(): Accepts an object as a parameterand returns the equivalent JSON string.

You can see the first one in action in our heroes-finished-on-parse.html example (see the source code) — this does exactly the same thing as the example we built up earlierexcept that:

  • we retrieve the response as text rather than JSONby calling the text() method of the response
  • we then use parse() to convert the text to a JavaScript object.

The key snippet of code is here:

async function populate() {
  const requestURL =
    "https://mdn.github.io/learning-area/javascript/oo/on/superheroes.on";
  const request = new Request(requestURL);

  const response = await fetch(request);
  const superHeroesText = await response.text();

  const superHeroes = JSON.parse(superHeroesText);
  populateHeader(superHeroes);
  populateHeroes(superHeroes);
}

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

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

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

Summary

In this lessonwe've introduced you to using JSON in your programsincluding how to create and parse JSONand how to access data locked inside it. In the next articlewe'll give you some tests that you can use to check how well you've understood and retained all this information.

See also