简体   繁体   English

如何使用备注将 Markdown 解析为 json

[英]How to parse markdown to json using remark

The remark site has a link to an AST explorer for the output of remark - https://astexplorer.net/#/gist/0a92bbf654aca4fdfb3f139254cf0bad/ffe102014c188434c027e43661dbe6ec30042ee2备注站点有一个链接到 AST 浏览器,用于备注输出 - https://astexplorer.net/#/gist/0a92bbf654aca4fdfb3f139254cf0bad/ffe102014c188434c027e43661dbe6ec30042ee2

What I cannot find is how to do the parsing to AST - all the examples convert to html.我找不到的是如何对 AST 进行解析 - 所有示例都转换为 html。

I have this code我有这个代码


import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm' // git flavoured markdown

const content = `
# My header

This is my content

 - abc
 - def
 
`;

unified()
    .use(remarkParse)
    .use(remarkGfm)
    .process('# Hi\n\n*Hello*, world!')
    .then((file) => {
        console.log(String(file))
    })

but am getting a couple of errors here that I do not know how to get around但我在这里遇到了一些错误,我不知道如何解决

[remark-gfm] Warning: please upgrade to remark 13 to use this plugin
file:///markdown/node_modules/unified/lib/index.js:520
    throw new TypeError('Cannot `' + name + '` without `Compiler`')
          ^

TypeError: Cannot `process` without `Compiler`

You almost have it.你几乎拥有它。 Below I've simplified your code, removing unused and unnecessary parts.下面我简化了您的代码,删除了未使用和不必要的部分。

import {unified} from 'unified'
import remarkParse from 'remark-parse'

let myResult = unified()
    .use(remarkParse)
    .parse('# Hi\n\n*Hello*, world!');

console.log(JSON.stringify(myResult, null, "   "));

According to ChristianMurphy's GitHub Q/A :根据ChristianMurphy 的 GitHub 问答

unified.process() will try to take text, turn it into an AST, and back into text. Unified.process() 将尝试获取文本,将其转换为 AST,然后再转换为文本。

For your stated purpose, " ...parsing to AST [JSON]", you don't need or want the " full-cycle process " that unified.process() is failing to complete, TypeError: Cannot 'process' without 'Compiler' .出于您所述的目的,“ ...解析为 AST [JSON]”,您不需要或不想要unified.process()未能完成的“全周期过程”, TypeError: Cannot 'process' without 'Compiler' You merely want to parse the input and emit the syntax tree (AST) as JSON.您只想解析输入并将语法树 (AST) 作为 JSON 发出。 The error here is because process() , after parsing your input (markdown string) and turning it into a syntax tree (AST), is then trying to " compile " it to some output format.这里的错误是因为process()在解析您的输入(降价字符串)并将其转换为语法树(AST)之后,然后尝试将其“编译”为某种输出格式。 However, you haven't supplied a compiler.但是,您尚未提供编译器。 But, as I understand your post, you don't need or want to compile the syntax tree into another output (language).但是,据我了解您的帖子,您不需要或不想将语法树编译成另一种输出(语言)。 So, change from process() to parse() and emit the resulting syntax tree as JSON.因此,从process()更改为parse()并将结果语法树作为 JSON 发出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM