![](/img/trans.png)
[英]How can I validate & beautify JSON through a jquery/javascript plugin
[英]How can I beautify JSON programmatically in angular js?
我知道如何使用javascript以编程方式美化JSON。 这样我们可以实现:
var obj = {"hello":"world", "Test":["hello"]}
document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(obj, null, 4)));
但是我试图用angular js做到这一点。 但我无法实现这一目标。 这是我的步骤:
<div class="btn btn-primary" ng-click="test()">Press</div>
<textarea json-formatter rows="20" cols="140" ng-model="json">
</textarea>
$scope.test=function(){
var json=JSON.stringify($scope.json, null, "\t");
/*here if $scope.json is {"hello":"world", "Test":["hello"]}
then json return "{\"hello\":\"world\", \"Test\":[\"hello\"]}" */
}
如果$scope.json
是{"hello":"world", "Test":["hello"]}
则json
返回"{\\"hello\\":\\"world\\", \\"Test\\":[\\"hello\\"]}"
。之后,我现在不介绍如何将美化json显示到相同的文本区域。 如何解决这个问题。 还有其他方法可以建议我吗?
您可以为代码使用内置的过滤器
{{dataObject | json}}
将美化您的json,请尝试一下。
这是一个工作示例:
您可以使用Angular内置的json
过滤器漂亮地打印对象。
在您看来,可以按以下方式使用过滤器:
{{yourData | json}}
可以通过将第二个数值传递到过滤器中来定制缩进:
{{yourData | json:4}}
可以在以下位置找到此代码的有效示例: http : //jsbin.com/nakazuhaqa/1/edit?html,js,output
Angular为此提供了一个帮助器:
angular.toJson(json, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.