从文件到js获取JSON值

时间:2016-03-14 12:44:54

标签: javascript jquery json

我有一个json文件,它以这种形式保存数据:

{
  "UserEmail": "email@domain.com",
  "UserAvatar": "url",
  "Username": "Name",
  "Contacts": [
    "email2@domain.com",
    "emai3l@domain.com"
  ],
  "MyFriends": [
    "",
    ""
  ],
  "MyEnemies": [
    "",
    ""
  ],
  "FriendsAvatar": {
    "email2@domain.com": "url2",
    "email3@domain.com": "url3"
  }
}

我想将数据传递给js数组,所以当我需要一个值来调用相应的键时。对于array_json['UserEmail'],我会得到email@domain.comarray_json['Contacts']另一个带有联系信息的数组。

我在这里搜索过去的问题,但每当我尝试使用$.getJSON() JQuery函数时,我都会收到错误。

以下是我的想法:

var obj = [];
  $.ajax({
    url: "json/HV.json",
    success: function (data) {
        obj = JSON.parse(data);
        alert(obj);
        }
    });

1 个答案:

答案 0 :(得分:0)

您不需要使用解析函数。它可以按如下方式访问

 $.ajax({
   url: "json/HV.json",
   success: function (data) {
      alert(data.UserEmail);
   }
 });

看到它正在使用此代码段

var data = {
  "UserEmail": "email@domain.com",
  "UserAvatar": "url",
  "Username": "Name",
  "Contacts": [
    "email2@domain.com",
    "emai3l@domain.com"
  ],
  "MyFriends": [
    "",
    ""
  ],
  "MyEnemies": [
    "",
    ""
  ],
  "FriendsAvatar": {
    "email2@domain.com": "url2",
    "email3@domain.com": "url3"
  }
}

alert(data.UserEmail)