1

我对 json 很陌生,我似乎无法访问它正确的变量。

例如,我正在尝试获取“用户名”,以便可以为 AngularJS 项目创建模拟。

$httpBackend.expectGET('user.json').
  respond(Users[ { Username: "bjarnipolo"}, { Username: "yolo"} ]);


{
  "Users":[
      {
      "UserId":1,
      "Username":"bjarnipolo",
      "Password":null,
      "FirstName":"Bjarni Póló",
      "LastName":"Súkkulaðisson",
      "Ssn":"2412813539",
      "Email":"bjarnip08@ru.is",
      "Phone":"6903066",
      "Roles":"Stjornandi",
      "JobTitle":"Scrum Master",
      "ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
      "IsActive":true
      },
      {
      "UserId":2,
      "Username":"yolo",
      "Password":null,
      "FirstName":"Brynjólfur YOLO",
      "LastName":"Hermannsson",
      "Ssn":"0106752040",
      "Email":"Binni@example.com",
      "Phone":"8995555",
      "Roles":"Notandi",
      "JobTitle":"Team member",
      "ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
      "IsActive":true
      }
  ]
}
4

1 回答 1

1

我想我找到了一个解决方案来得到你想要的。

您可以使用new Request.JSON. 请求应如下所示:

new Request.JSON({
 url: '/echo/json/',
 data: {
    json: JSON.encode({
          "Users":[
              {
              "UserId":1,
              "Username":"bjarnipolo",
              "Password":null,
              "FirstName":"Bjarni Póló",
              "LastName":"Súkkulaðisson",
              "Ssn":"2412813539",
              "Email":"bjarnip08@ru.is",
              "Phone":"6903066",
              "Roles":"Stjornandi",
              "JobTitle":"Scrum Master",
              "ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
              "IsActive":true
              },
              {
              "UserId":2,
              "Username":"yolo",
              "Password":null,
              "FirstName":"Brynjólfur YOLO",
              "LastName":"Hermannsson",
              "Ssn":"0106752040",
              "Email":"Binni@example.com",
              "Phone":"8995555",
              "Roles":"Notandi",
              "JobTitle":"Team member",
              "ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
              "IsActive":true
              }
         ]
     }),
 },
 onSuccess: function(response) {
    var jsonObj = response;
    alert(jsonObj.Users[1].Username);

    jsonObj.Users[1].Username = "dsds";

    alert(jsonObj.Users[1].Username);
 }
}).send();

这是jsFiddle

于 2013-06-10T13:05:41.367 回答