본문 바로가기
css

대응에서 구문 강조를 통해 JSON을 예쁜 인쇄로 표시

by code-box 2022. 3. 9.
반응형

img

이 게시물에서는 RespectJS/JS 앱에서 컬러로 강조 표시된 구문과 함께 JSON 데이터를 인쇄된 것으로 표시하는 방법에 대해 알아보겠습니다.

바로 아래의 유틸리티 기능으로 넘어가겠습니다.


export function syntaxHighlight(json) {
    if (!json) return ""; //no JSON from response

    json = json
      .replace(/&/g, "&")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");
    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>
  );
}

효용함수 크레딧

 

댓글