[英]How can I beautify JSON programmatically in angular js?
I know how to beautify JSON programmatically using javascript. 我知道如何使用javascript以编程方式美化JSON。 this way we can achieve: 这样我们可以实现:
var obj = {"hello":"world", "Test":["hello"]}
document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(JSON.stringify(obj, null, 4)));
But i tried to do it in angular js. 但是我试图用angular js做到这一点。 but i am unable to achieve this. 但我无法实现这一目标。 This is my step : 这是我的步骤:
<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\"]}" */
}
here if $scope.json
is {"hello":"world", "Test":["hello"]}
then json
return "{\\"hello\\":\\"world\\", \\"Test\\":[\\"hello\\"]}"
.after that, i don't now how to display beautify json to same text area. 如果$scope.json
是{"hello":"world", "Test":["hello"]}
则json
返回"{\\"hello\\":\\"world\\", \\"Test\\":[\\"hello\\"]}"
。之后,我现在不介绍如何将美化json显示到相同的文本区域。 How to resolve this problem. 如何解决这个问题。 Is there any other approach then please suggest me ? 还有其他方法可以建议我吗?
You can use the built in filter for your code 您可以为代码使用内置的过滤器
{{dataObject | json}}
Will beautify your json, give it a try. 将美化您的json,请尝试一下。
Here is a working example: 这是一个工作示例:
http://plnkr.co/edit/DM1TbN3eXGngJaFgi6n6?p=preview http://plnkr.co/edit/DM1TbN3eXGngJaFgi6n6?p=preview
You can use Angular's built in json
filter to pretty print an object. 您可以使用Angular内置的json
过滤器漂亮地打印对象。
In your view you can use the filter as follows: 在您看来,可以按以下方式使用过滤器:
{{yourData | json}}
The indentation can be customised by passing a second numerical value into the filter: 可以通过将第二个数值传递到过滤器中来定制缩进:
{{yourData | json:4}}
A working example of this code can be found here: http://jsbin.com/nakazuhaqa/1/edit?html,js,output 可以在以下位置找到此代码的有效示例: http : //jsbin.com/nakazuhaqa/1/edit?html,js,output
Angular provides a helper for this: Angular为此提供了一个帮助器:
angular.toJson(json, true);
https://docs.angularjs.org/api/ng/function/angular.toJson https://docs.angularjs.org/api/ng/function/angular.toJson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.