Github API 更新 json 文件

Github API update json file

我正在使用 Github 目录 API 更新存储库中的 .json 文件,但它似乎没有按预期工作。这是客户端(浏览器)请求。

基本上,我有一个 json 文件,我想向其中添加一个新的 JSON 对象。对象的结构是

id: ''
isEnabled: true

使用内容 API 我可以创建提交,但它看起来像这样 -

这是负责创建和推送提交对象的代码

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,
    //     }),
    //   }
    // );

我不确定在这种情况下我做错了什么。

假设 modifiedContent 是一个有效的 JSON 对象:

对于 NodeJS:

const updatedContent = Buffer.from(JSON.stringify(modifiedContent), "utf8").toString("base64")

对于浏览器:

const updatedContent = btoa(JSON.stringify(content))

然后继续构建您的请求,如上所示。

要使用您提到的 API,您的代码应类似于:

const originalContent = await getFromOrigin(...);

const modifiedContent = await getUpdatedContentFromEditor(...);

const updatedContent = btoa(modifiedContent);

编辑 1:添加了浏览器和 NodeJS 变体。
编辑 2:添加了更多上下文。