JSON 格式字符串输出

我有一个 AngularJS 应用程序,它从输入中收集数据,使用 JSON.stringify()将模型转换为字符串,并允许用户编辑这个模型,如果 <textarea>元素被更新,则输入字段得到更新,反之亦然。某种双向绑定:)

问题是 String 本身看起来很丑,我想把它格式化成这样:

enter image description here

而且不像现在看起来的那样:

enter image description here

有什么办法吗?如果你需要一些额外的信息-不要犹豫问。每一个回答都会受到高度赞赏并立即得到回答。

谢谢你。

另外,我想这应该是某种指令或者自定义过滤器。数据本身不应该被改变,只有输出。

203589 次浏览

You can use an optional parameter of JSON.stringify()

JSON.stringify(value[, replacer [, space]])

Parameters

  • value The value to convert to a JSON string.
  • replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
  • space Causes the resulting string to be pretty-printed.

For example:

JSON.stringify({a:1,b:2,c:{d:3, e:4}},null,"    ")

will give you following result:

"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"

Angular has a built-in filter for showing JSON

<pre>\{\{data | json}}</pre>

Note the use of the pre-tag to conserve whitespace and linebreaks

Demo:

angular.module('app', [])
.controller('Ctrl', ['$scope',
function($scope) {


$scope.data = {
a: 1,
b: 2,
c: {
d: "3"
},
};


}
]);
<!DOCTYPE html>
<html ng-app="app">


<head>
<script data-require="angular.js@1.2.15" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>
</head>


<body ng-controller="Ctrl">
<pre>\{\{data | json}}</pre>
</body>


</html>

There's also an angular.toJson method, but I haven't played around with that (Docs)

If you are looking to render JSON as HTML and it can be collapsed/opened, you can use this directive that I just made to render it nicely:

https://github.com/mohsen1/json-formatter/

enter image description here

In addition to the angular json filter already mentioned, there is also the angular toJson() function.

angular.toJson(obj, pretty);

The second param of this function lets you switch on pretty printing and set the number of spaces to use.

If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

If you want to format the JSON and also do some syntax highlighting, you can use the ng-prettyjson directive. See the npm package.

Here is how to use it: <pre pretty-json="jsonObject"></pre>

I guess you want to use to edit the json text. Then you can use ivarni's way:

\{\{data | json}}
and add an adition attribute to make
 editable

<pre contenteditable="true">\{\{data | json}}</pre>

Hope this can help you.