html怎样格式化输出JSON数据


本文摘自PHP中文网,作者php中世界最好的语言,侵删。

这次给大家带来html怎样格式化输出JSON数据,html格式化输出JSON数据的注意事项有哪些,下面就是实战案例,一起来看一下。

将 json 数据以美观的缩进格式显示出来,借助最简单的 JSON.stringify 函数就可以了,因为此函数还有不常用的后面2个参数。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<html>

    <head>

        <meta charset="utf-8" />

        <title>hello</title>

        <style>

            pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }

            .string { color: green; }

            .number { color: darkorange; }

            .boolean { color: blue; }

            .null { color: magenta; }

            .key { color: red; }

        </style>

        <script type="text/javascript">

        function syntaxHighlight(json) {

            if (typeof json != 'string') {

                json = JSON.stringify(json, undefined, 2);

            }

            json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');

            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {

                var cls = 'number';

                if (/^"/.test(match)) {

                    if (/:$/.test(match)) {

                        cls = 'key';

                    } else {

                     cls = 'string';

                    }

                } else if (/true|false/.test(match)) {

                    cls = 'boolean';

                } else if (/null/.test(match)) {

                    cls = 'null';

                }

                return '<span class="' + cls + '">' + match + '</span>';

            });

        }

    </script>

    </head>

    <body>

    <pre id="result">

    </pre>

    <script type="text/javascript">

        var songResJson={

              "service": "ALL",

             "qt": 581,

               "content": {

                "answer": {

               "song": "如果缘只到遇见",

                  "album": "如果缘只到遇见",

                  "artist": "吴奇隆 严艺丹",

                  "pic_url": "http://p1.music.126.net/-u3WgIXsFNCW7d8Jy7pCEA==/5921969627395387.jpg"

                },

                "scene": "music"

             }

            }

            document.getElementById('result').innerHTML = syntaxHighlight(songResJson);

        // $('#result').html(syntaxHighlight(songResJson));

    </script>

    </body>

</html>

相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

阅读剩余部分

相关阅读 >>

html基础知识

为什么普遍使用json?

html标记是什么

如何解决javascript乱码问题

jquery+jsonp跨域需要怎样实现

html网页特效代码有哪些

javascript函数前面加!、+、-、~, ;符号的意义介绍

html5中关于div与span html块级元素的详细介绍

html文件怎么转换成jsp文件

聊聊javascript人脸识别技术

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...