javascript – 使用TypeScript将JSON(从Sentry)转换为HTML

前端之家收集整理的这篇文章主要介绍了javascript – 使用TypeScript将JSON(从Sentry)转换为HTML前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想学习TypeScript.

我有一个由sentry方法event_from_exception()(Python)返回的JSON字典.

我想将它格式化为带有可扩展局部变量和pre_和post_context的漂亮HTML.结果应该大致如下:

这是json的一个例子:

{
  "exception": {
    "values": [
      {
        "stacktrace": {
          "frames": [
            {
              "function": "main","abs_path": "/home/modlink_cok_d/src/sentry-json.py","pre_context": [
                "from sentry_sdk.utils import event_from_exception","","def main():","    local_var = 1","    try:"
              ],"lineno": 9,"vars": {
                "exc": "ValueError()","local_var": "1"
              },"context_line": "        raise ValueError()","post_context": [
                "    except Exception as exc:","        event,info = event_from_exception(sys.exc_info(),with_locals=True)","        print(json.dumps(event,indent=2))","main()"
              ],"module": "__main__","filename": "sentry-json.py"
            }
          ]
        },"type": "ValueError","value": "","module": "exceptions","mechanism": null
      }
    ]
  },"level": "error"
}

怎么能用TypeScript完成?

解决方法

>为数据创建架构.这将有助于您使用TypeScript和IDE.

你可以使用https://app.quicktype.io给你.

export interface Welcome {
    exception: Exception;
    level:     string;
}

export interface Exception {
    values: Value[];
}

export interface Value {
    stacktrace: Stacktrace;
    type:       string;
    value:      string;
    module:     string;
    mechanism:  null;
}

export interface Stacktrace {
    frames: Frame[];
}

export interface Frame {
    function:     string;
    abs_path:     string;
    pre_context:  string[];
    lineno:       number;
    vars:         Vars;
    context_line: string;
    post_context: string[];
    module:       string;
    filename:     string;
}

export interface Vars {
    exc:       string;
    local_var: string;
}

>从数据中渲染HTML.

你可以使用template literal
如果您不喜欢Web框架(React,Vue).

const data = JSON.parse(json);
const html = `
    <div>${data.exception.values.map(value => `
        <div>${value.stacktrace.frames.map(frame => `
            <div>
                <pre>${frame.abs_path} in ${frame.function}</pre>
                <div style="margin-left:2rem">
                    ${frame.pre_context.map((line,i) =>`
                        <pre>${frame.lineno + i - frame.pre_context.length}. ${line}</pre>
                    `).join("")}

                    <pre><strong>${frame.lineno}. ${frame.context_line}</strong></pre>
                    ${frame.post_context.map((line,i) => `
                        <pre>${frame.lineno + i + 1}. ${line}</pre>
                    `).join("")}
                </div>
            </div>
        `).join("")}</div>
    `).join("")}</div>
`;
document.body.innerHTML = html;

例如:https://codesandbox.io/s/52x8r17zo4

原文链接:https://www.f2er.com/js/156326.html

猜你在找的JavaScript相关文章