如何用JS和HTML制作JSON格式化程序?

问题描述 投票:0回答:3

我的 Web 应用程序需要一个使用 Angular JS 和 Java 开发的 JSON 格式化程序。

我基本上想要这样的 JSON 格式化程序,在其格式化视图中显示 JSON。我想要格式化程序,因为通常当我在 html 中渲染 JSON 文本时,它会像一堆文本一样显示。

这就是为什么我想制作 JSON 格式化程序以在格式化视图中显示这些 JSON 文本。它将帮助用户轻松理解 JSON。

在我的应用程序中,用户出于不同目的输入 JSON。例如,管理员输入/修改 JSON 以生成动态字段。 JSON 文本将存储在数据库中。 我想为所有目的制作一个通用的 JSON 格式化程序。如果不可能,不同的操作使用不同的 JSON 格式化程序。

有些人建议我使用 JSON.stringify()。但我怎样才能用它来达到我的目的呢?或者还有其他想法吗?

javascript html json angularjs formatter
3个回答
0
投票

JSON.stringify
就是您要找的东西

JSON.stringify(jsonObject, null, 4); // stringify with spaces (recommended)
JSON.stringify(jsonObject, null, '\t'); // stringify with tabs

现实世界的例子:

<html>
    <body>
        <pre>
            <div id="stringifiedCode">

            </div>
        </pre>
    </body>
</html>

<script type="text/javascript">
var obj = { "hello" : "world", "Test" : [ "hello" ] };
document.getElementById('stringifiedCode').innerHTML =JSON.stringify(obj, null, 4);
</script>

0
投票

HTML:

<div ng-app="myapp" ng-controller="myctrl">
    <pre>{{ str|json }}</pre>
</div>

脚本:

angular.module('myapp',[])
 .controller('myctrl',function($scope){
     $scope.str = {name:'Joe',address:'xyz',mobile:['154552','45698']};
  });

笨蛋


0
投票

您可以使用以下工具轻松格式化 JSON:JSON Formatter Tool。只需粘贴您的 JSON,它就会为您格式化。

© www.soinside.com 2019 - 2024. All rights reserved.