简体   繁体   English

(ES6)无法访问JSON数据(未定义错误)

[英](ES6) Can't get acces to JSON data (undefined error)

I have this JSON file with data about 2 contacts. 我有这个JSON文件,其中包含有关2个联系人的数据。

{
   "results":[
      {
         "gender":"female",
         "name":{
            "title":"Ms",
            "first":"Leonie",
            "last":"Otto"
         },
         "location":{
            "street":"3076 raiffeisenstraße",
            "city":"meißen",
            "state":"sachsen-anhalt",
            "postcode":62480
         },
         "email":"leonie.otto@example.com",
         "login":{
            "username":"bigwolf465",
            "password":"stephane",
            "salt":"Ip5qcgs5",
            "md5":"fe5df54750c64b7c5d54c92f0cb91f11",
            "sha1":"17d255fb64135b5e247a4ef5554557a1d2a8881e",
            "sha256":"341d750fce611b853b4f27d485f10ef9f9c3add4de12a7fbf838a1fd2d5168a9"
         },
         "dob":"1955-01-08 01:03:55",
         "registered":"2012-07-07 16:42:10",
         "phone":"0265-7006038",
         "cell":"0178-0561111",
         "id":{
            "name":"",
            "value":null
         },
         "picture":{
            "large":"https://randomuser.me/api/portraits/women/8.jpg",
            "medium":"https://randomuser.me/api/portraits/med/women/8.jpg",
            "thumbnail":"https://randomuser.me/api/portraits/thumb/women/8.jpg"
         },
         "nat":"DE",
         "status": "online"
      },
      {
         "gender":"female",
         "name":{
            "title":"Miss",
            "first":"Olive",
            "last":"Wright"
         },
         "location":{
            "street":"2912 manukau road",
            "city":"timaru",
            "state":"otago",
            "postcode":30721
         },
         "email":"olive.wright@example.com",
         "login":{
            "username":"brownrabbit413",
            "password":"derek",
            "salt":"gRxy7hHq",
            "md5":"dc214ffe467373790c8500abd1ff0f8f",
            "sha1":"7b7847e1a9e3b3de081e3eeebf972dc5d2b5527a",
            "sha256":"1763dff5c43e1cea431d1ad8c1648c586af9d1e1410001d743078af143ce30b9"
         },
         "dob":"1982-07-01 12:12:29",
         "registered":"2016-03-25 19:15:33",
         "phone":"(003)-127-5232",
         "cell":"(133)-307-2001",
         "id":{
            "name":"",
            "value":null
         },
         "picture":{
            "large":"assets/img/users/233899238.jpg"
         },
         "nat":"NZ",
         "status": "online"
      }
   ],
   "info":{
      "seed":"0c15ba34c943fa7f",
      "results":10,
      "page":1,
      "version":"1.1"
   }
}

I want to make a list where I show all the contacts from the JSON file. 我想做一个清单,在其中显示JSON文件中的所有联系人。 I want to show the name, picture and username. 我想显示名称,图片和用户名。 I try to do that with this js code: 我尝试使用以下js代码来做到这一点:

{

  const createContacts = results => {

    const $li = document.createElement(`li`);
    $li.classList.add(`contact`);
    $li.dataset.username = results.login.username;
    document.querySelector(`.contacts-list`).appendChild($li);

    const $divWrap = document.createElement(`div`);
    $divWrap.classList.add(`wrap`);
    $li.appendChild($divWrap);

    const $span = document.createElement(`span`);
    $span.classList.add(`contact-status ${results.status}`);
    $divWrap.appendChild($span);

    const $img = document.createElement(`img`);
    $img.src = results.picture.large;
    $img.setAttribute(`alt`, `${results.name.first}`);
    $divWrap.appendChild($img);

    const $divMeta = document.createElement(`div`);
    $divMeta.classList.add(`meta`);
    $li.appendChild($divMeta);

    const $name = document.createElement(`p`);
    $name.classList.add(`name`);
    $name.textContent = `${results.name.first} ${results.name.last}`;
    $divMeta.appendChild($name);

    const $preview = document.createElement(`p`);
    $preview.classList.add(`preview`);
    $preview.textContent = `${results.login.username}`;
    $divMeta.appendChild($preview);

  };

  const makeContacts = results => {
    results.forEach(result => {
      createContacts(results);
    });
  };
  const parse = results => {
    makeContacts(results);
  };

  const init = () => {
    const jsonFile = `./assets/data/users.json`;
    fetch(jsonFile).then(r => r.json()).then(data => parse(data.results));

  };
  init();
}

I keep getting this error. 我不断收到此错误。

script.js:7 Uncaught (in promise) TypeError: Cannot read property 'username' of undefined

Does someone know what I do wrong? 有人知道我做错了吗? It seems like I can't get acces to the JSON data. 看来我无法访问JSON数据。

You are passing results array to createContacts(results); 您正在将results数组传递给createContacts(results);

Change it to below: 将其更改为以下内容:

const makeContacts = results => {
    results.forEach(result => {
      createContacts(result);
    });
  }; 

You pass the results array to your function createContacts . 您将results数组传递给函数createContacts Change it like so: 像这样更改它:

const makeContacts = results => {
    results.forEach(result => {
      createContacts(result);
    });
};

As results is a list and not an object you can't just type results.login as this will return undefined. 由于results是一个列表而不是一个对象,因此您不能只键入results.login因为这将返回undefined。 Alternatively you may use index of result for example results[0].login.username . 或者,您可以使用结果索引,例如results[0].login.username

The best approach here is loop through the results array. 最好的方法是遍历结果数组。

const createContacts = results => {
    results.forEach(item => {
        const $li = document.createElement(`li`);
        $li.classList.add(`contact`);
        $li.dataset.username = item.login.username;
        document.querySelector(`.contacts-list`).appendChild($li);
    })
    ...
    ...
}

You are passing the results array to your createContacts function instead of the result (single element of that array). 您将results数组传递给createContacts函数,而不是result (该数组的单个元素)。

You could fix it by changing your code like so: 您可以通过更改代码来修复它,如下所示:

const makeContacts = results => {
  results.forEach(result => {
    createContacts(result);
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM