从api url打印json数据

时间:2016-10-20 09:45:06

标签: javascript jquery json api

我有问题将json对象解析为文本。任何人都可以帮助我吗?

这是我的代码:

<script>
  $.ajax({
   url: 'https://randomuser.me/api/',
    dataType: 'json',
    success: function(data) {
    var jsonString = data;
    var myJsonObject = JSON.parse(jsonString);
    alert(myJsonObject);
    }
 });
</script>

这是我的回答:

{
"results": [
  {
    "gender": "male",
    "name": {
      "title": "mr",
      "first": "noah",
    "last": "chan"
  },
  "location": {
    "street": "5316 brock rd",
    "city": "lafontaine",
    "state": "new brunswick",
    "postcode": 88811
  },
  "email": "noah.chan@example.com",
  "login": {
    "username": "silverlion343",
    "password": "pacific",
    "salt": "YQfKuRwc",
    "md5": "72faf6fd29f245b028655fc423919b5b",
    "sha1": "5f9c0106ac18b7ea4a15ad53667dc49fc644aa1c",
    "sha256":   "42465b6f63942f01c96149dd7e725f5b0e5b6836e0ce0a66b62559ff8a8e706a"
  },
  "dob": "1962-05-21 10:51:27",
  "registered": "2004-12-24 02:34:01",
  "phone": "655-165-7871",
  "cell": "548-005-8204",
  "id": {
    "name": "",
    "value": null
  },
  "picture": {
    "large": "https://randomuser.me/api/portraits/men/27.jpg",
    "medium": "https://randomuser.me/api/portraits/med/men/27.jpg",
    "thumbnail": "https://randomuser.me/api/portraits/thumb/men/27.jpg"
  },
  "nat": "CA"
}
],
"info": {
"seed": "bc96983e110ad6ea",
"results": 1,
"page": 1,
"version": "1.1"
}
}

这是我的控制台日志:

  

SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符

     

var myJsonObject = JSON.parse(jsonString);

似乎我错过了一些明显的东西.... 提前致谢

1 个答案:

答案 0 :(得分:2)

在您提供dataType时,响应已经被反序列化了。删除JSON.parse()行并直接使用data作为对象,您的代码应该可以正常工作。

另请注意,您应使用console.log()console.dir()进行调试,而不是alert()

&#13;
&#13;
$.ajax({
  url: 'https://randomuser.me/api/',
  dataType: 'json',
  success: function(data) {
    console.log(data);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;