Как красиво напечатать (украсить) строку JSON

Метод JSON stringify возвращает строку JSON из массива или объекта. Этот метод ожидает 3 параметра:

  • значение (объект или массив)
  • Replacer или Filter (функция для обработки или массив строк с показанными индексами)
  • пробел (довольно распечатать ваш JSON с пробелами или разрывы строк)
var value = {
hello:"Hey!",
bye: "Ok bye!",
id:123
}; // An array or an object
//A function that alters the behavior of the stringification process,
// or an array of Strings and Numbers objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string.
// If this value is null or undefined, all properties of the object are included in the resulting JSON string
var replacer = ["hello"];
// or a function
// In this case only the id property of the object will be stringified as this is the only property with a numeric value.
function replacer(key, value) {
if (typeof value === "number") {
return undefined;
}
return value;
}
// a numeric value which is identified as spaces
// or use custom separators (line breaks \t or \n )
var space = 5;
JSON.stringify(value, replacer, space);

Вы можете красиво распечатать объект json, используя третий параметр. Очень полезно, если вы работаете с cordova или node.js для создания организованных файлов .json.

В следующем примере показано, как правильно напечатать (с отступом json) объект json с помощью JSON.stringify и задать стиль выделения с помощью css:

syntaxHighlight Функция добавит к каждому свойству диапазон с пользовательским классом, чтобы придать эффект подсветки в элементе div. Вы можете даже выделить стиль в консоли Chrome, используя CSS, Подробнее о том, как css работает в консоли, читайте здесь.

Следующая функция будет обрабатывать сгенерированную симпатичную строку json JSON.stringify функция и напечатает его с цветами в консоли.

function PrettyPrintJsonConsole(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, '\t');
}
var
arr = [],
_string = 'color:green',
_number = 'color:darkorange',
_boolean = 'color:blue',
_null = 'color:magenta',
_key = 'color:red';
json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var style = _number;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
style = _key;
} else {
style = _string;
}
} else if (/true|false/.test(match)) {
style = _boolean;
} else if (/null/.test(match)) {
style = _null;
}
arr.push(style);
arr.push('');
return '%c' + match + '%c';
});
arr.unshift(json);
console.log.apply(console, arr);
}
var myCustomObject = {
numbers:[1,3,4,5],
hello:"Hey there!",
otherThing:true,
anotherThing:4
};
PrettyPrintJsonConsole(JSON.stringify(myCustomObject,null,4));

Использование предыдущей функции должно вывести что-то вроде этого в консоли Chrome:

Chrome pretty-print JSON

Повеселись !

Ссылка на основную публикацию
Adblock
detector