将markdown转换为json对象 [英] convert markdown to json object

查看:1625
本文介绍了将markdown转换为json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过Webpack加载器导入到这样的节点模块中的markdown文件

I have a markdown file imported in a node module like this through a webpack loader

import mardownFile from './markdownfile.md'

此文件是一本教科书,各章之间用##/h2标签分隔

this file is a text book with chapters separated by a ## / h2 tag

现在,我正在寻找一种将其转换为带有每个h2标签(或其他可能的包装器)的json对象的方法,这些对象位于单独的章节块中,以与页面内容为props.children的react页面组件一起使用.有关我要解决的问题的更多详细信息

now, I'm looking for a way to convert this into a json object with each h2 tag (or other possible wrapper) in separate chapter chunks to use with a react page component with the page content as props.children. More details on what I'm trying to solve

我的markdown.md文件中有这个

I have this in my markdown.md file

#Title
##Chapter 1
text text
text
##Chapter 2
text
etc
##Chapter 3
more text
image

我想阅读此markdown并将其转换为对象,诸如此类...

I would like to read this markdown and convert it to an object, something like this...

var aText = {
pages: [
{
 "title": "Chapter 1.",
 "text": "text",
},
{
"title": "Chapter 2.",
"text": "text",
},
{
"title": "Chapter 3.",
"text": "text",
"img": "cat-stevens.png",
}
]}

然后在javascript react组件中呈现这样的Page组件

Then in a javascript react component render a Page component like this

<Page page={aText.pages[0]} />

我使用的是Mac osx计算机,但这是个人Web客户端项目,我试图在标准浏览器中进行解析,我使用的是Chrome,什么是实现这一目标的最佳方法?有什么建议吗?

I'm on a mac osx computer but this is personal web client project, I was trying to parse this in a standard browser, i'm using Chrome, What's the best approach to accomplish this, any suggestions?

推荐答案

您无法导入md文件,因为只能在javascript文件上导入. 您需要使用某些markdown解析器或编写自己的解析器.例如 markdown-it :

You can not import md file, because import for only on javascript files. You need use some markdown parser or write your own. For example markdown-it:

var MarkdownIt = require('markdown-it');
var md = new MarkdownIt();
var result = md.parse('# markdown-it rulezz!');
console.log(result);

您将获得:

[Token {
  type: 'heading_open',
  tag: 'h1',
  attrs: null,
  map: [0, 1],
  nesting: 1,
  level: 0,
  children: null,
  content: '',
  markup: '#',
  info: '',
  meta: null,
  block: true,
  hidden: false
},
  Token {
  type: 'inline',
  tag: '',
  attrs: null,
  map: [0, 1],
  nesting: 0,
  level: 1,
  children: [[Object]],
  content: 'markdown-it rulezz!',
  markup: '',
  info: '',
  meta: null,
  block: true,
  hidden: false
},
  Token {
  type: 'heading_close',
  tag: 'h1',
  attrs: null,
  map: null,
  nesting: -1,
  level: 0,
  children: null,
  content: '',
  markup: '#',
  info: '',
  meta: null,
  block: true,
  hidden: false
}]

这篇关于将markdown转换为json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆