• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023 Fujian Newland Auto-ID Tech.Co.,Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15import hilog from '@ohos.hilog';
16/**
17 * 格式化JSON数据
18 * @param jsonObj 需要转换的数据
19 */
20const TAG: string = '[Sample_DeviceManagement]';
21const DOMAIN : number = 0xFF00;
22function transitionJsonToString(jsonObj: string): string {
23  // 转换后的jsonObj受体对象
24  let _jsonObj: string = null;
25  // 判断传入的jsonObj对象是不是字符串,如果是字符串需要先转换为对象,再转换为字符串,这样做是为了保证转换后的字符串为双引号
26  if (Object.prototype.toString.call(jsonObj) !== '[object String]') {
27    try {
28      _jsonObj = JSON.stringify(jsonObj);
29    } catch (error) {
30      // 转换失败错误信息
31      errorLog(JSON.stringify(error));
32    }
33  } else {
34    try {
35      jsonObj = jsonObj.replace(/(\')/g, '"');
36      _jsonObj = JSON.stringify(JSON.parse(jsonObj));
37    } catch (error) {
38      // 转换失败错误信息
39      errorLog(JSON.stringify(error));
40    }
41  }
42  return _jsonObj;
43}
44
45function errorLog(...args: string[]): void {
46  hilog.error(DOMAIN, TAG, '%{public}s', args);
47}
48
49/**
50 * 格式化JSON数据
51 * @param jsonObj 需要转换的数据
52 */
53export function formatJson(jsonObj: string): string {
54  let formatted: string = '';
55  // 换行缩进位数
56  let pad: number = 2;
57  // 一个tab对应空格位数
58  let PADDING: string = '\t';
59  // json对象转换为字符串变量
60  let jsonString: string = transitionJsonToString(jsonObj);
61  if (!jsonString) {
62    return jsonString;
63  }
64  // 将jsonString字符串内容通过\r\n符分割成数组
65  let jsonArray: Array<string> = [];
66  // 正则匹配到{,}符号则在两边添加回车换行
67  jsonString = jsonString.replace(/([\{\}])/g, '\r\n$1\r\n');
68  // 正则匹配到[,]符号则在两边添加回车换行
69  jsonString = jsonString.replace(/([\[\]])/g, '\r\n$1\r\n');
70  // 正则匹配到,符号则在两边添加回车换行
71  jsonString = jsonString.replace(/(\,)/g, '$1\r\n');
72  // 正则匹配到要超过一行的换行需要改为一行
73  jsonString = jsonString.replace(/(\r\n\r\n)/g, '\r\n');
74  // 正则匹配到单独处于一行的,符号时需要去掉换行,将,置于同行
75  jsonString = jsonString.replace(/\r\n\,/g, ',');
76  // 特殊处理双引号中的内容
77  jsonArray = jsonString.split('\r\n');
78  // 将处理后的数组通过\r\n连接符重组为字符串
79  jsonString = jsonArray.join('\r\n');
80  // 将匹配到:后为回车换行加大括号替换为冒号加大括号
81  jsonString = jsonString.replace(/\:\r\n\{/g, ':{');
82  // 将匹配到:后为回车换行加中括号替换为冒号加中括号
83  jsonString = jsonString.replace(/\:\r\n\[/g, ':[');
84  // 将上述转换后的字符串再次以\r\n分割成数组
85  jsonArray = jsonString.split('\r\n');
86  // 将转换完成的字符串根据PADDING值来组合成最终的形态
87  jsonArray.forEach(function (item, index) {
88    let i: number = 0;
89    // 表示缩进的位数,以tab作为计数单位
90    let indent: number = 0;
91    // 表示缩进的位数,以空格作为计数单位
92    let padding: string = '';
93    if (item.match(/\{$/) || item.match(/\[$/)) {
94      // 匹配到以{和[结尾的时候indent加1
95      indent += 1;
96    } else if (item.match(/\}$/) || item.match(/\]$/) || item.match(/\},$/) || item.match(/\],$/)) {
97      // 匹配到以}和]结尾的时候indent减1
98      if (pad !== 0) {
99        pad -= 1;
100      }
101    } else {
102      indent = 0;
103    }
104    for (i = 0; i < pad; i++) {
105      padding += PADDING;
106    }
107    formatted += padding + item + '\r\n';
108    pad += indent;
109  });
110  // 返回的数据需要去除两边的空格和换行
111  return formatted.trim().replace(new RegExp('^\\' + '<br />' + '+|\\' + '<br />' + '+$', 'g'), '');
112}