반응형
img
이 게시물에서는 RespectJS/JS 앱에서 컬러로 강조 표시된 구문과 함께 JSON 데이터를 인쇄된 것으로 표시하는 방법에 대해 알아보겠습니다.
바로 아래의 유틸리티 기능으로 넘어가겠습니다.
export function syntaxHighlight(json) {
if (!json) return ""; //no JSON from response
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>";
}
);
}
그리고 CSS
pre {
outline: 1px solid #ccc;
padding: 5px;
margin: 15px;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
이제 구문Highlight 기능을 사용하여 JSON과 함께 전달하면 예쁘고 강조 표시됩니다.
ReactJS 앱의 사용 예:
import { useEffect, useState } from "react";
import { syntaxHighlight } from "./utils";
import "./styles.css";
export default function App() {
const [ourJSON, setOurJSON] = useState();
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((json) => setOurJSON(json));
}, []);
return (
<div>
<h3 className="header">
Show JSON As Pretty Print With Syntax Highlighting
</h3>
<pre
dangerouslySetInnerHTML={
__html: syntaxHighlight(JSON.stringify(ourJSON, undefined, 4))
}
/>
</div>
);
}
효용함수 크레딧
'css' 카테고리의 다른 글
해시 및 해시 테이블 (0) | 2022.03.09 |
---|---|
CSS 셀렉터가 뭐야? CSS 선택기는 어떻게 작동합니까? (0) | 2022.03.09 |
스타일링된 구성요소의 사용자 지정 구성요소에 오신 것을 환영합니다! (0) | 2022.03.09 |
CSS 캐스케이드 레이어를 사용한 계층화 (0) | 2022.03.09 |
뉴 캐스케이드로부터의 질문들 (0) | 2022.03.09 |
댓글