来自 JSON 字符串的 AngularJS 对象

AngularJS Object from JSON String

本文关键字:AngularJS 对象 字符串 JSON 来自      更新时间:2023-09-26

我有一个看起来像这样的 Angular 对象(menuItems 包含更多数据,但这不是重点):

$scope.data = {
   title:'Title',
   place:'Somewhere'
   menuItems: [{
        title: "This is a Title",
        name: "John"},
                {
        title: "Another Title",
        name: "Frank"} ]
};

我使用默认值创建此 $scope.data。它们总是相同的。此数据用于使用 ng-model 填充 html 页面。以及 ng 重复调用以显示所有菜单项。

<input class="text form-control" ng-model="data.title"></div>
<div ng-repeat="item in data.menuItems">
   <input class="text form-control" ng-model="item.name"></div>
   ...
</div>

然后,我成功地将数据对象导出为 JSON 字符串,如下所示:

$scope.json = angular.toJson($scope.data, false);

这会产生一个类似于这个的 JSON 字符串:

{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}

我现在要做的是加载这个 JSON 字符串并覆盖 $scope.data 对象(提供修改现有 JSON 字符串的方法)。

我像这样加载字符串:

var json = JSON.stringify("{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}");
$scope.data = JSON.parse(json);

但是没有更新任何数据,并且在 ng 重复中创建的所有div 都会消失。

我无法更改 JSON 的结构,因为它在另一个应用程序中以这种方式使用。有没有办法实现我想要的?

谢谢。

由于您正在使用$scope.json = angular.toJson($scope.data, false);因此在角度中执行相反操作的方法将angular.fromJson($scope.json) .

还要确保您的 JSON 有效。 即"{"menuItems":[{"title":"This is a title","name":"John"},{"title":"Another Title","name":"Frank"}],"title":"Title", "place":"Somewhere"}")看起来您的内部引号没有转义,或者您不使用单引号作为外部引号。

你必须转义引号:

var json = JSON.parse("{'"menuItems'":[{'"title'":'"This is a title'",'"name'":'"John'"},{'"title'":'"Another Title'",'"name'":'"Frank'"}],'"title'":'"Title'", '"place'":'"Somewhere'"}");

你也在串弦! JSON.stringify 需要对象并返回 JSON 字符串。