I'm using the Github Contents API to update a .json
file within a repo, but it doesn't seem to work as expected. This is a client-side (browser) request.
Basically, I have a json
file and I would like to add a new JSON
object to it. The structure of the object is
id: ''
isEnabled: true
With the Contents API I am able to create the commit but it sort of looks like this -
This is the code that is responsible for creating and pushing the commit object
let updatedContent = utf8.decode(base64.encode(modifiedContent));
console.log(updatedContent);
// const commit = await fetch(
// `${GITHUB_HOST}/repos/${OWNER}/${REPO}/contents/src/components.json`,
// {
// method: 'PUT',
// headers: AuthService.getAuthServiceInstance().withGithubAuthHeaders({
// 'Content-Type': 'application/json',
// }),
// body: JSON.stringify({
// path: 'src/components.json',
// content: updatedContent,
// sha,
// message,
// branch: activeBranch,
// }),
// }
// );
I'm not sure what I'm doing incorrect in this case.
Assuming modifiedContent
is a valid JSON Object:
For NodeJS:
const updatedContent = Buffer.from(JSON.stringify(modifiedContent), "utf8").toString("base64")
For Browser:
const updatedContent = btoa(JSON.stringify(content))
Then proceed to construct your request as you've shown above.
To use the API you've mentioned, you're code would look something like:
const originalContent = await getFromOrigin(...);
const modifiedContent = await getUpdatedContentFromEditor(...);
const updatedContent = btoa(modifiedContent);
Edit 1: Added the browser and NodeJS variants.
Edit 2: Added more context.