javascript - 如何根据来自多个降价文件的数据编写 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 文件。
我怎样才能做到这一点?感谢所有帮助和建议。
解决方案
我使用节点而不是 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
.
推荐阅读
- java - 如何使用 Jackson @JsonFormat 注解格式化序列化字符串?
- django - 将图像名称保存到数据库中 - Django
- nginx - 如何使用 Docker 部署使用外部登录提供程序的应用程序?
- c++ - 如何将智能指针从函数传递给调用者?
- java - 在 @RequestPayload 中获取 NULL
- sql - 我想在 PostgreSQL 的同一列中从另一个品牌中删除一些与一个品牌相关的客户
- nginx - 如何将 url/abc 重定向到 url/abc/live-preview,其中 abc 是变量名?
- java - 如何使用查询删除数据库中的行?
- javascript - javascript石头剪刀布游戏()函数中的循环功能和计数
- python - 通过队列中的特殊对象通过队列终止多线程处理是否合理?