我正在尝试在Angular中使用JSON文件,但参考文件不是真正的JSON。访问它并将其解析为真正的JSON以便使用的最佳方法是什么?

我正在尝试在angular.js的控制器中访问notTrue.json,就像下面的文件结构一样。并将notTrue.json解析为真实的JSON格式。

示例文件结构:

index.html
js (folder)
 - angular.js
 - notTrue.json
 - etc
css (folder)
img (folder)


示例非JSON格式的notTrue.json文件:

var Foo = [{
    'bar': 'Hello World',
    'subItem': {
        'phone1': '(555) 543-213',
        'email': 'foo@bar.com'
    }
}, {
    'bar': 'Goodnight Moon',
    'subItem': {
        'phone1': '(555) 521-3344',
        'email': 'foo2@bar.com'
    }
}];


我想将其转换为正确的JSON格式,如下所示:

[{
    "bar": "Hello World",
    "subitem": {
        "phone1": "(555) 543-213",
        "email": "foo@bar.com"
    }
}, {
    "bar": "Goodnight Moon",
    "subitem": {
        "phone1": "(555) 521-3344",
        "email": "foo2@bar.com"
    }
}]

最佳答案

如果此notTrue.json文件是静态的,就意味着在用户访问index.html时该文件已经存在并且在用户使用该应用程序期间不会更改,那么最好通过notTrue.json包含script标签,在加载angular.js之前,如下所示:

<script src="js/notTrue.json"></script>
<script src="js/angularjs"></script>


然后,您将可以访问应用程序中的Foo对象。以下代码通过在屏幕上输出JSON格式来说明这一点:

<div ng-app="myApp" ng-controller="myControler">
   <pre>{{json}}</pre>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myControler', function($scope, $window) {
        // window.Foo was defined when loading notTrue.js
        // Convert it to JSON string (pretty printed)
        $scope.json = JSON.stringify($window.Foo, null, 4);
    });
</script>


在上面的示例中,页面上的输出将是:

[
    {
        "bar": "Hello World",
        "subItem": {
            "phone1": "(555) 543-213",
            "email": "foo@bar.com"
        }
    },
    {
        "bar": "Goodnight Moon",
        "subItem": {
            "phone1": "(555) 521-3344",
            "email": "foo2@bar.com"
        }
    }
]


请注意,pre标记和JSON.stringify方法的额外参数用于获取漂亮打印的JSON字符串。但这对您的问题不是必需的。

动态加载notTrue.js

另一方面,如果您想推迟加载notTrue.js直到某个事件发生,因为它的内容可能在页面加载和该事件之间改变,那么您可以使用$http.get

在以下示例中,单击按钮即加载文件,并且在屏幕上输出JSON格式:

<div ng-app="myApp" ng-controller="myControler">
   <button ng-click="load('js/notTrue.json')">Load</button>
   <pre>{{json}}</pre>
</div>

<script>
    var app = angular.module('myApp', []);
    app.controller('myControler', function($scope, $http) {
        // Define what should happen on button click:
        $scope.load = function(file) {
            $http.get(file).then(function(response) {
                // Extract from the retrieved file contents
                // the part between the first "=" and
                // final (optional) semi-colon
                var txt = response.data.replace(/^.*?=([\S\s]*?);?\s*$/, '$1');
                // Evaluate that text, adding brackets to avoid misinterpretation
                // when text starts with opening brace.
                var Foo = eval('(' + txt + ')');
                // and convert to JSON string (pretty printed)
                $scope.json = JSON.stringify(Foo, null, 4);
            });
        };
    });
</script>


输出与第一个解决方案相同。

请注意,使用这种方法,加载的文件必须驻留在同一服务器上,据我了解,这是您的情况。

仅在第一个解决方案不符合您的需求时才采用此解决方案。

您将需要添加检查并处理可能的错误,以查找何时找不到文件,格式不正确等。

最后,请小心使用eval:仅当您信任源时才使用它,我相信这里就是这种情况。

10-07 18:59
查看更多