golang markdown转 json
文章目录[隐藏]
代码
package main
import (
"encoding/json"
"io/ioutil"
"log"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text"
)
// MarkdownNode 表示 Markdown 节点的结构
type MarkdownNode struct {
Type string `json:"type"`
Content string `json:"content,omitempty"`
Language string `json:"language,omitempty"`
Children []MarkdownNode `json:"children,omitempty"`
}
// 将 AST 节点转换为自定义节点结构
func convertNode(n ast.Node, source []byte) MarkdownNode {
node := MarkdownNode{
Type: n.Kind().String(),
}
if n.Kind() == ast.KindFencedCodeBlock {
}
//node.Content = string(n.Text(source))
//获取节点内容
//if n.Kind() == ast.KindText || n.Kind() == ast.KindCodeBlock {
// node.Content = string(n.Text(source))
//}
switch n.Kind() {
case ast.KindText:
node.Content = string(n.Text(source))
case ast.KindFencedCodeBlock:
if cb, ok := n.(*ast.FencedCodeBlock); ok {
var content string
lines := cb.Lines()
for i := 0; i < lines.Len(); i++ {
line := lines.At(i)
content += string(line.Value(source))
}
node.Content = content
// 如果需要获取代码块的语言信息
if len(cb.Language(source)) > 0 {
node.Language = string(cb.Language(source))
}
}
}
// 处理子节点
if n.HasChildren() {
child := n.FirstChild()
for child != nil {
node.Children = append(node.Children, convertNode(child, source))
child = child.NextSibling()
}
}
return node
}
func main() {
// 读取 Markdown 文件
source, err := ioutil.ReadFile("/Users/wulili/Desktop/mycode/aliCode/simulatorBackend/test/input.md")
if err != nil {
log.Fatal(err)
}
// 创建 Markdown 解析器
md := goldmark.New()
reader := text.NewReader(source)
doc := md.Parser().Parse(reader)
// 转换为自定义节点结构
rootNode := MarkdownNode{
Type: "document",
}
// 遍历 AST
child := doc.FirstChild()
for child != nil {
rootNode.Children = append(rootNode.Children, convertNode(child, source))
child = child.NextSibling()
}
// 转换为 JSON
jsonData, err := json.MarshalIndent(rootNode, "", " ")
if err != nil {
log.Fatal(err)
}
// 写入文件
err = ioutil.WriteFile("output.json", jsonData, 0644)
if err != nil {
log.Fatal(err)
}
}
input.md
# 标题
这是一段文本。
- 列表项1
- 列表项2
## 二级标题
```代码块
fmt.Println("Hello")
```
output.json
{
"type": "document",
"children": [
{
"type": "Heading",
"children": [
{
"type": "Text",
"content": "标题"
}
]
},
{
"type": "Paragraph",
"children": [
{
"type": "Text",
"content": "这是一段文本。"
}
]
},
{
"type": "List",
"children": [
{
"type": "ListItem",
"children": [
{
"type": "TextBlock",
"children": [
{
"type": "Text",
"content": "列表项1"
}
]
}
]
},
{
"type": "ListItem",
"children": [
{
"type": "TextBlock",
"children": [
{
"type": "Text",
"content": "列表项2"
}
]
}
]
}
]
},
{
"type": "Heading",
"children": [
{
"type": "Text",
"content": "二级标题"
}
]
},
{
"type": "FencedCodeBlock",
"content": "fmt.Println(\"Hello\")\n",
"language": "代码块"
}
]
}
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。
转载请注明来源:golang markdown转 json - 多知在线