繁体   English   中英

如何在angular js中以编程方式美化JSON?

[英]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显示到相同的文本区域。 如何解决这个问题。 还有其他方法可以建议我吗?

有一个用于过滤json {{Object | json}}

您可以为代码使用内置的过滤器

{{dataObject | json}} 

将美化您的json,请尝试一下。

这是一个工作示例:

http://plnkr.co/edit/DM1TbN3eXGngJaFgi6n6?p=preview

您可以使用Angular内置的json过滤器漂亮地打印对象。

在您看来,可以按以下方式使用过滤器:

{{yourData | json}}

可以通过将第二个数值传递到过滤器中来定制缩进:

{{yourData | json:4}}

可以在以下位置找到此代码的有效示例: http : //jsbin.com/nakazuhaqa/1/edit?html,js,output

Angular为此提供了一个帮助器:

angular.toJson(json, true);

https://docs.angularjs.org/api/ng/function/angular.toJson

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM