javascript 使用 Generate Ionic 使用 AngularJS 将 JSON 字符串反序列化为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25829315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:06:19  来源:igfitidea点击:

Deserialise JSON String to Object with AngularJS using Generate Ionic

javascriptjsonangularjsdeserialization

提问by Luke Schoen

I am following this AngularJS Tutorial.

我正在关注这个AngularJS 教程

I am successfully able to display a data model array list in the browser (Chrome 37.0.2062.94) when instantiated using object literal notation, where $scope.sentences is of type "Object".

使用对象文字表示法实例化时,我能够成功地在浏览器(Chrome 37.0.2062.94)中显示数据模型数组列表,其中 $scope.sentences 的类型为“Object”。

Controller: (extract)

控制器:(摘录)

'use strict';
angular.module('YeomanIonic.controllers', [])
.controller('MapCtrl', ['$scope', '$ionicLoading', '$http', function($scope, $ionicLoading, $http) {
$scope.sentences = [
  {"name": "Hello",
   "snippet": "1"
  },
  {"name": "Goodbye", 
   "snippet": "2"
  }
];
}]);

View (extract):

查看(摘录):

  <body ng-app="YeomanIonic" ng-controller="MapCtrl">
            <ul>
              <li ng-repeat="sentence in sentences">
                <span>{{sentence.name}}</span>
                <p>{{sentence.snippet}}</p>
              </li>
            </ul>

But I get problems when I instead store this array of hashes in a JSON file (i.e. app/data/sentences.json), as follows:

但是,当我将这个哈希数组存储在 JSON 文件(即 app/data/sentences.json)中时出现问题,如下所示:

sentences.JSON:

句子.JSON:

[
  {"name": "Hello",
   "snippet": "1"
  },
  {"name": "Goodbye", 
   "snippet": "2"
  }
];

I attempt to use the AngularJS $http service to perform a HTTP GET request to fetch this JSON data. The tutorial mentions that AngularJS detects and parses the JSON response automatically and that the $http service returns a promise object with a success method. So I assumed that the following code would work correctly such that $scope.sentences would be of type "Object", however it informs me that it is of type "String".

我尝试使用 AngularJS $http 服务来执行 HTTP GET 请求以获取此 JSON 数据。本教程提到 AngularJS 会自动检测和解析 JSON 响应,并且 $http 服务返回一个带有成功方法的 promise 对象。所以我假设下面的代码可以正常工作,这样 $scope.sentences 将是“Object”类型,但是它告诉我它是“String”类型。

  $http({
    method: 'GET', 
    url: 'data/sentences.json'
  }).
    success(function(data, status, headers, config) {
      console.log("HTTP Request - Success");
      $scope.sentences = data;
      console.log(typeof($scope.sentences));
    }).
    error(function(data, status, headers, config) {
      console.log("HTTP Request - Error");
    });

So I attempted to assign it with this following code instead, which gives the following error:

所以我试图用下面的代码来分配它,这给出了以下错误:

$scope.sentences = angular.fromJson(data);

SyntaxError: Unexpected token ;
    at Object.parse (native)
    at Object.fromJson (http://127.0.0.1:9000/bower_components/angular/angular.js:1139:14)
    at http://127.0.0.1:9000/scripts/controllers.js:34:59
    at http://127.0.0.1:9000/bower_components/angular/angular.js:8105:11
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11561:81)
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11561:81)
    at http://127.0.0.1:9000/bower_components/angular/angular.js:11647:26
    at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12673:28)
    at Scope.$digest (http://127.0.0.1:9000/bower_components/angular/angular.js:12485:31)
    at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12777:24) angular.js:10061

I try the below alternative with quotations included, which gives the following error (which is getting confused with the letter 'd' in the word 'data') :

我尝试以下包含引号的替代方法,这会产生以下错误(与“数据”一词中的字母“d”混淆):

$scope.sentences = angular.fromJson('data');

SyntaxError: Unexpected token d
    at Object.parse (native)
    at Object.fromJson (http://127.0.0.1:9000/bower_components/angular/angular.js:1139:14)
    at http://127.0.0.1:9000/scripts/controllers.js:34:59
    at http://127.0.0.1:9000/bower_components/angular/angular.js:8105:11
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11561:81)
    at wrappedCallback (http://127.0.0.1:9000/bower_components/angular/angular.js:11561:81)
    at http://127.0.0.1:9000/bower_components/angular/angular.js:11647:26
    at Scope.$eval (http://127.0.0.1:9000/bower_components/angular/angular.js:12673:28)
    at Scope.$digest (http://127.0.0.1:9000/bower_components/angular/angular.js:12485:31)
    at Scope.$apply (http://127.0.0.1:9000/bower_components/angular/angular.js:12777:24) angular.js:10061

I try this third alternative, which gives the same as the previous error:

我尝试了第三种选择,它给出了与上一个错误相同的错误:

$scope.sentences = window.JSON.parse('data');

I try a fourth alternative, which also gives the same as the previous error:

我尝试了第四种选择,它也给出了与上一个错误相同的错误:

$scope.sentences = JSON.parse('data');

With little hope left I came across this [lifesaver post] (https://stackoverflow.com/a/6487190/3208553) that mentioned using eval('data'), but which also mentions that it presents a security risk, but I gave it a shot with:

几乎没有希望我遇到了这个 [lifesaver post] ( https://stackoverflow.com/a/6487190/3208553) 提到使用 eval('data'),但也提到它存在安全风险,但我试了一下:

$scope.sentences = eval(data);

And this works!! It successfully grabs and displays the data from the JSON file as a list in the browser. Note that when I check what it assigns with console.log(eval(data)); it gives me [object Object],[object Object],[object Object],[object Object]

这有效!!它成功地从 JSON 文件中抓取数据并将其显示为浏览器中的列表。请注意,当我使用 console.log(eval(data)); 检查它分配的内容时;它给了我 [object Object],[object Object],[object Object],[object Object]

But I can't celebrate because I don't understand why the other alternatives that I tried didn't work...

但我无法庆祝,因为我不明白为什么我尝试过的其他替代方案不起作用......

So my questions to the community are:

所以我向社区提出的问题是:

  1. Why doesn't the AngularJS $http service detect and parses the JSON response automatically and return it as an Object (instead of a String)?
  2. Why doesn't the AngularJS fromJSONdeserialize the JSON string without an error? (which appears to simply perform JSON.parse('') according to its Source Code)
  3. Is my JSON encoding competent and are my inputs incorrectly validated in this simple example? Is this why only the unsafe 'eval' method works for me (with its associated security risks)?
  1. 为什么 AngularJS $http 服务不自动检测和解析 JSON 响应并将其作为对象(而不是字符串)返回?
  2. 为什么 AngularJS fromJSON 不会反序列化 JSON 字符串而不会出错?(它似乎只是根据其源代码执行 JSON.parse('') )
  3. 我的 JSON 编码是否能够胜任?我的输入是否在这个简单示例中被错误验证?这就是为什么只有不安全的“评估”方法对我有用(及其相关的安全风险)?

FYI, Hereis the latest commit to my Ionic app associated with this post on GitHub

仅供参考,是与 GitHub 上的这篇文章相关的对我的 Ionic 应用程序的最新提交

回答by Nadeem Khoury

I fixed this bug after finding a missing comma in my JSON file.

在我的 JSON 文件中找到一个缺少的逗号后,我修复了这个错误。