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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...