微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/js/156326.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐