簡體   English   中英

將對象寫入現有 json 文件並用 '[ ]' 包裝內容

[英]Writing an object to an existing json file and wrapping the contents with '[ ]'

好的,所以我通過編寫一個實用程序來學習javascript(來自c++),該實用程序接收.md(markdown)文件並將文件解析/轉換為html然后到json對象,然后將該對象寫入現有的json文件以遵循我的規范的格式。

要清楚,請參閱以下管道:

循環瀏覽 .md 文件的目錄->通過解析/轉換階段推送每個文件,該階段將 Markdown 轉換為 html ->將 html 和解析的數據推送到 json 文件

請注意,我已經完成了大部分邏輯,但是,我需要有關格式問題的幫助...請在關閉或回答之前閱讀完整的帖子。 謝謝!

流水線的主要邏輯:

export function transformMdtoHtmltoJson(dest, post) {
    
    const file = matter.read(post);
    
    const title = file.data.title;
    const date = file.data.date;
    const description = file.data.description;
    const socials = file.data.socials;
    
    unified()
        .use(remarkParse)
        .use(remarkRehype)
        .use(rehypeStringify)
        .process(file.content)
        .then(
            (result) => {
                toJson(dest, title, date, description, result.value, socials);
            },
            (err) => {
                throw err;
            }
          );
}

我的插件將 json 寫入現有文件:

class Data {

  constructor(title, date, description, content, socials) {
    this.title = title;
    this.date = date;
    this.description = description;
    this.content = content;
    this.socials = socials;
  }
}


function createNewMember(title, date, description, content, socials) {
        let newMemer = new Data(title, date, description, content, socials);
        let result = {};
        return result = {
                "title": newMemer.title,
                "date": newMemer.date,
                "description": newMemer.description,
                "content": newMemer.content,
                "socials": newMemer.socials
        }
}

export async function toJson(inFile, title, data, description, content, socials) {
  const rl = readline.createInterface({
    input: fs.createReadStream(inFile),
    crlfDelay: Infinity,
  });
  const lines = [];
  for await (const line of rl) {
    lines.push(line);
  }
  let object = createNewMember(title, data, description, content, socials);
  lines.push(JSON.stringify(object));
  let string = lines.join('') + ',';
  writeFile(inFile, string);
}

function writeFile(inFile, data) {
          fs.writeFile(inFile, data, { flag: "a+" }, (err) => {
                            if (err) throw err;
                            console.log("The file has been saved!");
                          }
                          );
}

我的輸入:帖子目錄~/path/to/posts/post1.md ~/path/to/posts/post2.md ~/path/to/posts/post3.md

帖子的內容(每個帖子都一樣,以使事情變得簡單)

---
title: Hello this is a test
date: 05/04/2022
description: this is a test
socials:
---

# Hello
## subhello

我的目標: ~/path/to/post.json

我的入口點功能:

const postDir = path.join(process.cwd(), 'posts');
const destDir = path.join(process.cwd(), '_data');
const jsonFile = 'post.json';

const fileNames = fs.readdirSync(postDir);

async function generatePosts(fileNames, postDir, destDir, jsonFile) {
          fileNames.forEach( (fileName) => {
                        const fullPath = path.join(postDir, fileName);
                        const destPath = path.join(destDir, jsonFile)
                        transformMdtoHtmltoJson(destPath, fullPath);
                });
}


generatePosts(fileNames, postDir, destDir, jsonFile);

我的輸出: ~/path/to/post.json

{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null},
{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null},
{"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null
},

我想要做的是將此輸出包裝在 [ ] 括號中,以便我可以將它們作為數組循環。

期望的輸出:

[
{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null},
{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null},
{"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null
},
]

我嘗試了幾種方法,但它們都只是用 [ ] 包裝每個單獨的帖子,導致

[{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null}],
[{
"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null}],
[{"title":"Hello this is a test",
"date":"05/04/2022",
"description":"this is a test",
"content":"<h1>Hello</h1>\n<h2>subhello</h2>",
"socials":null
}],

這不是我想要的。 我曾認為也許用回調來做這件事會是解決方案,但我一直沒能把它做好。 請幫忙。

這是 github 存儲庫的鏈接https://github.com/giannicrivello/MarkdownToHtmlToJson

我想你可能走錯了路。 根據我對您的代碼的理解(使用我不熟悉的庫),您正在做的是為您擁有的每個 .md 文件編寫文件,這可能不是最有效的。

我會做什么,這樣你就不必重構你所做的:

export async function toJson(inFile, title, data, description, content, socials) {
  const buffer = fs.readFileSync(inFile);
  
  // Maybe "buffer.toString() ?? '[]';", not sure if that works
  // This is done to instanciate an empty array if the file is empty
  const fileContent = buffer.toString() ? buffer.toString() : '[]';

  // Parses the json into an array of objects.
  // (Obviously only works if the json file is empty or an array at root)
  var arrayOfObjects = JSON.parse(fileContent);
  
  // Puts your object at begging of the array
  // might as well use .push() if you want it at then end
  arrayOfObjects.unshift({
    title,
    data,
    description,
    content,
    socials,
  });
  
  // I REALLY recommend you use those extra arguments (null, 2)
  // or similar ones so your file don't look too wierd reading it
  writeFile(inFile, JSON.stringify(fullObjectArray, null, 2));
}

這可能不起作用,因為我無法真正嘗試您所做的事情,不知道如何下載軟件包,但它應該引導您以正確的方式解決您的問題:)

編輯:當你准備好你所做的事情時,我注意到函數createNewMember和類Data都可以被刪除並替換為你的toJson函數中的基本“對象聲明”。 如果您打算在其他地方重新使用它,您可以保留您的 Data 類......

編輯 2:我從您的代碼中刪除了所有不必要的內容,並使其僅寫入一次您的post.json文件。 整個事情可能是這樣的:

export function transformMdtoHtmltoJson(dest, post) {
  const file = matter.read(post);

  const { title, date, description, socials } = file.data;

  unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypeStringify)
    .process(file.content)
    .then(
      (result) => {
        // I used the fields you added in your exemple
        // but if you want ALL from file.data, i suggest
        // you remove the declaration of all those variables
        // and use object destructuration in this return
        // object instead:
        // return {
        //   ...file.data,
        //   content: result.value,
        // }
        return {
          title,
          date,
          description,
          content: result.value,
          socials,
        }
      },
      (err) => {
        throw err;
      }
    );
}
const postDir = path.join(process.cwd(), 'posts');
const destDir = path.join(process.cwd(), '_data');
const jsonFile = 'post.json';

const fileNames = fs.readdirSync(postDir);

generatePosts();

async function generatePosts() {
  const destPath = path.join(destDir, jsonFile)
  let posts = [];

  fileNames.forEach((fileName) => {
    const fullPath = path.join(postDir, fileName);
    posts.push(transformMdtoHtmltoJson(destPath, fullPath));
  });

  writeFile(destPath, JSON.stringify(posts, null, 2));
}

function writeFile(inFile, data) {
  fs.writeFile(inFile, data, { flag: "a+" }, (err) => {
    if (err) throw err;
      console.log("The file has been saved!");
    }
  );
}

但是在這里,我沒有嘗試過,所以你可能需要糾正一些我沒有想到的事情......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM