拆分json并使用ng-repeat angular directive

时间:2016-03-08 22:34:54

标签: javascript angularjs json parsing ng-repeat

如何查看拆分json字符串的Key: value列表?

function MyCtrl($scope) {

    var jsonString='{"prop":"1, 2, 3, 4, 5, 6", "prop": "lol, asd, lidfj", "prop": "asd, test!!!"}';
    $scope.evalled=$scope.$eval(jsonString);
    
    $scope.fromJsoned=angular.fromJson(jsonString);
    
  $scope.ljson = JSON.parse(jsonString);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
    <div ng-controller="MyCtrl">     
        <p>JSON.parse:</p>
        <ul>
        <li ng-repeat="son in ljson">Key: {{son.key }}, Value: {{son}}</li>
        </ul>
    </div>
</div>

在此示例中,目标是显示:

 - Key: prop, Value: 1, 2, 3, 4, 5, 6
 - Key: prop, Value: lol, asd, lidfj
 - Key: prop, Value: asd, test!!!

3 个答案:

答案 0 :(得分:1)

你的json字符串不是一个数组,ng-repeat需要重复这个数组。

你想要这个:

var jsonString='[{"prop":"1, 2, 3, 4, 5, 6"}, {"prop": "lol, asd, lidfj"}, {"prop": "asd, test!!!"}]';

答案 1 :(得分:1)

您可以使用ng-repeat="(key, value) in data"。然后您的代码变为

<li ng-repeat="(key, value) in ljson">Key: {{key }}, Value: {{value}}</li>

答案 2 :(得分:0)

剧本:

var obj = JSON.parse(jsonString);

var result = []
for (var key in obj){
    result.push({key:key, value: obj[key]});
}

$scope.ljson = result;

html:

<li ng-repeat="son in ljson">Key: {{son.key }}, Value: {{son.value}}</li>

不确定它会处理多个&#34; prop&#34;好吧,不过