convert markdown to json object

后端 未结 3 2000
抹茶落季
抹茶落季 2020-12-29 14:08

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

3条回答
  •  一生所求
    2020-12-29 14:52

    For my first search on this I've found the jsonmark package that is kinda what you have requested but it creates an object with order and contents which is not necessary and is hard to modify its code as it is based on regexp.

    I agree with galkin's response that using a markdown parser's tokens should get you what you want.

    Here is my example of how to create a json object based on markdown. My goal was to have a json array with elements that have a head and body, head is the h1 and body is all that goes beneath it. In the example I'm using marked as the markdown parser. (I'm Running it on nodejs as reading from file is not quite possible from file otherwise.)

    var fs = require('fs');
    var marked = require('./marked.min.js');
    var finally = [];
    var heading = '';
    var lexbody = [];
    
    var loadmd = function(file){
      var markdown = fs.readFileSync(file, 'utf8');
      jsonraw = marked.lexer(markdown);
      finally = [];
      heading = '';
      lexbody = [];
      jsonraw.forEach(getThem);
      return finally;
    }
    var getThem = function(item, index){
      if (item.type == "heading" && item.depth == 1){
        if (heading == ''){
          heading = item.text;
        } else {
          lexbody['links']=jsonraw.links;
          finally.push(
            {
              "heading": heading,
              "body": marked.parser(lexbody)
            }
          );
          heading = item.text;
          lexbody = [];
        }
      } else {
        lexbody.push(item);
      }
      // don't leave out the last element
      if (index == jsonraw.length-1){
        lexbody['links']=jsonraw.links;
        finally.push(
          {
            "heading": heading,
            "body": marked.parser(lexbody)
          }
        );
      }
    }
    

提交回复
热议问题