Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

javascript - convert markdown to json object

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

import mardownFile from './markdownfile.md'

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

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

I have this in my markdown.md file

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

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",
}
]}

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

You will get:

[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
}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...