Table of Contents
效果图
Home Web Front-end JS Tutorial Example code for js formatting json

Example code for js formatting json

Mar 02, 2018 pm 01:19 PM
javascript json format

本文主要和大家分享js格式化json的实例代码,希望能帮助到大家。

var jsonStr;// json字符串
Copy after login
// 格式化json字符串
var jsonFormat = formatJson(jsonStr);
Copy after login
// 工具方法
var formatJson = function(json, options) {
                    var reg = null,
                        formatted = '',
                        pad = 0,
                        PADDING = '    '; // one can also use '\t' or a different number of spaces
                    // optional settings
                    options = options || {};
                    // remove newline where '{' or '[' follows ':'
                    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
                    // use a space after a colon
                    options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;

                    // begin formatting...

                    // make sure we start with the JSON as a string
                    if (typeof json !== 'string') {
                        json = JSON.stringify(json);
                    }
                    // parse and stringify in order to remove extra whitespace
                    json = JSON.parse(json);
                    json = JSON.stringify(json);

                    // add newline before and after curly braces
                    reg = /([\{\}])/g;
                    json = json.replace(reg, '\r\n$1\r\n');

                    // add newline before and after square brackets
                    reg = /([\[\]])/g;
                    json = json.replace(reg, '\r\n$1\r\n');

                    // add newline after comma
                    reg = /(\,)/g;
                    json = json.replace(reg, '$1\r\n');

                    // remove multiple newlines
                    reg = /(\r\n\r\n)/g;
                    json = json.replace(reg, '\r\n');

                    // remove newlines before commas
                    reg = /\r\n\,/g;
                    json = json.replace(reg, ',');

                    // optional formatting...
                    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                        reg = /\:\r\n\{/g;
                        json = json.replace(reg, ':{');
                        reg = /\:\r\n\[/g;
                        json = json.replace(reg, ':[');
                    }
                    if (options.spaceAfterColon) {
                        reg = /\:/g;
                        json = json.replace(reg, ': ');
                    }

                    $.each(json.split('\r\n'), function(index, node) {
                        var i = 0,
                            indent = 0,
                            padding = '';

                        if (node.match(/\{$/) || node.match(/\[$/)) {
                            indent = 1;
                        } else if (node.match(/\}/) || node.match(/\]/)) {
                            if (pad !== 0) {
                                pad -= 1;
                            }
                        } else {
                            indent = 0;
                        }

                        for (i = 0; i < pad; i++) {
                            padding += PADDING;
                        }

                        formatted += padding + node + '\r\n';
                        pad += indent;
                    });

                    return formatted;
                };
Copy after login

效果图

相关推荐:

html怎样格式化json数据

格式化Json传递日期的方法

html格式化json的实例代码

The above is the detailed content of Example code for js formatting json. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) May 04, 2024 pm 06:01 PM

Nowadays, we will inevitably encounter some problems such as being unable to turn on the phone or lagging, such as system crash, but during use, mobile phones have become an indispensable part of our lives. We are often at a loss, and sometimes, there are no solutions to these problems. To help you solve cell phone problems, this article will introduce you to some methods of cell phone format recovery and restore your phone to normal operation. Back up data - protect important information, such as photos and contacts, from being lost during the formatting process. Before formatting your phone, the first thing to consider is to back up important data and files on your phone. To ensure data security, or choose to transfer files to a cloud storage service, you can back it up by connecting to a computer. Use the system's built-in recovery function - simple

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

What are the methods of html formatting? What are the methods of html formatting? Mar 08, 2024 am 09:53 AM

HTML formatting method: 1. Use online HTML formatting tools; 2. Use the HTML formatting shortcut keys that come with the code editor, such as Shift + Alt + F in Visual Studio Code; 3. Use plug-ins, such as Sublime Text HTML/CSS/JS Prettify plug-in; 4. Use command line tools, such as HTML Tidy; 5. Manual formatting according to coding standards and habits.

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

How to format and reinstall the win10 system_Format and reinstall the win10 system tutorial How to format and reinstall the win10 system_Format and reinstall the win10 system tutorial Mar 21, 2024 pm 04:56 PM

Nowadays, the security of Windows 10 system computers is threatened by many viruses and programs. Let’s take a typical example. When he is surfing the Internet, he will unintentionally open a link or website, and then some very annoying advertisements will pop up on our computer inexplicably. Or if the computer is stuck in the interface and cannot move, it is likely that some software has been maliciously bundled and installed. Another situation is that there is a virus in the computer. If this kind of problem occurs, we can reinstall the system on the win10 computer, which can effectively remove the virus programs in the system disk. Now the editor will show you how to format and reinstall the win10 system. Let's read on. . 1. How to format and reinstall the win10 system? First, we click &quot;Start&quot; -

See all articles