首页 > 解决方案 > 如何根据来自多个降价文件的数据编写 JSON 文件

问题描述

我需要使用我的降价文件中的数据构建一个 API。

我有大约 100 个降价文件,文件顶部有这样的数据:

---
title: Lorem ipsum
category: component
primaryKeywords: curved horizon
secondaryKeywords: css block content seperator
---

所需的输出是单个 .json 文件,其中包含我的 .md 文件中的所有数据作为数组中的对象。

例子:

[
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  },
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  },
  {
    "title": "Lorem ipsum",
    "category": "component",
    "primaryKeywords": "curved horizon",
    "secondaryKeywords": "css block content seperator"
  }
]

JSON 文件应作为我的前端构建的一部分生成。我正在使用吞咽。

我试过做这样的事情:

gulp.task('search-api', function (cb) {
  const fs = require('fs');
  const matter = require('gray-matter');
  const str = fs.readFileSync('./src/docs/01-Components/02-Layout/03-bow.md', 'utf8');
  console.log(matter(str));
});

我可以在控制台中显示来自 1 个文件的数据。但我需要帮助来显示所有文件中的数据./src/docs/,然后将其合并为 1 个结果并将其解析为 1 个 JSON 文件。

我怎样才能做到这一点?感谢所有帮助和建议。

标签: javascriptnode.jsjsongulpmarkdown

解决方案


我使用节点而不是 gulp 将其作为“练习”进行:

const fs = require('fs');
const glob = require('glob');
const os = require('os');

const markdownFiles = glob.sync("./markdown/*.md");  // an array of files in the 'markdown' directory
let finalArray = [];


function buildJSONfile() {

  let contents;

  markdownFiles.forEach((nextFile) => {

    contents = fs.readFileSync(nextFile, "UTF8");

        // os.EOL = \r\n for windows, \n for POSIX
    let grayMatter = contents.match(new RegExp(`---${os.EOL}((.*${os.EOL})*?)---`));  // get just the content between the "---"s in array[1]

    //  add quotes around all the keys and values and add commas between key:value pairs
    let addedQuotes = grayMatter[1].replace(/^([^:]*)(:\s*)(.*)(\s*)/mg, '"$1"$2"$3",');  

    addedQuotes = addedQuotes.slice(0, addedQuotes.length - 1);  // remove the extra comma at the end of the last value

    let addedBrackets = `{${addedQuotes}}`;  // add brackets around the whole thing so that we can use JSON.parse

    let JSONobject = JSON.parse(addedBrackets);

    finalArray.push(JSONobject);
  });

      // write to a file : result.json
  fs.writeFileSync("./result.json", JSON.stringify(finalArray, null, '\t'), "UTF8");
};

buildJSONfile();  // comment out if using gulp

运行node yourFileNameHere.js
您也可以将其放入 gulpfile.js 并通过gulp buildJSONfile.


推荐阅读