Hello - I am using the Netlify CMS to create my blog posts, (they are a collection type) and Next JS as my frontend. I would like to fetch the data from my blog posts from a single .json file which I can fetch using the Github API. My issue is that the CMS is exporting each post as their own .json file for example:
- public
- posts
- post-one.json
- post-two.json
It makes it hard because I have to fetch each individual file.
Instead I would prefer a single file that contains an array of all my data as objects.
public/posts/one-file-with-all-data.json
Inside this file it could look like. ( or something similar.)
This is not possible. Netlify CMS is meant to edit and store posts individually. You cannot get a single JSON. You can create a GitHub Action, or some other automation to merge all this in a single JSON though.
Thank you for the response. This sounds like a solution but I was unable to create the build process when I experimented with Github actions. I will ask the question here in case someone catches it and can answer.
I used this found script to convert my .md files in a single .json file. It works locally when I use node but did not work as a github action.
// filename: buildJson.js
const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
const getAll = dir => {
// Read files at _posts/{directory}
const directory = path.join(process.cwd(), `content/${dir}`);
const fileNames = fs.readdirSync(directory);
// Get the content of the files as JSON
const content = fileNames.map((fileName, index) => {
const slug = fileName.replace(/\.md$/, "");
const fullPath = path.join(directory, fileName);
const fileContents = fs.readFileSync(fullPath, "utf8");
const matterResult = matter(fileContents);
return {
id: index + 1, slug, ...matterResult
};
});
// Return a big array of JSON
return JSON.stringify(content);
};
const allPosts = getAll("blog");
const postFileContents = `${allPosts}`;
// Create the cache folder if it doesn't exist
try {
fs.readdirSync("public/cache");
} catch (e) {
fs.mkdirSync("public/cache");
}
// Create our cached posts JSON
fs.writeFile("public/cache/posts.json", postFileContents, err => {
if (err) return console.log(err);
console.log("Posts cached.");
});
Hi, @frankiejrey. The purpose of this support forum is primarily to provide technical support for Netlify and the service we provide.
You can ask questions about GitHub actions here but our support team does provide technical support for GitHub itself. Someone else might answer this question and you are welcome to ask it here. However, this question is outside our support team’s scope of support.
I just wanted to explain why our support team will not be answering this question so you are not waiting for an answer from us.