![](/img/trans.png)
[英]Angularjs, output a string or an array of strings from json object
[英]AngularJS Object from JSON String
我有一個看起來像這樣的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-repeat調用。
<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-repeat中創建的所有div都會消失。
我無法更改JSON的結構,因為在其他應用程序中以這種方式使用了它。 有沒有辦法實現我想要的?
謝謝。
由於您正在使用$scope.json = angular.toJson($scope.data, false);
在angular中進行相反操作的方法是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字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.