Skip to content

Provide usage examples #97

@fregante

Description

@fregante

Already asked in #74, but it was closed by the author.

The request still stands, it would be great to have a few examples to use the library to load/parse/write JSONC files.

I shouldn't need to ask LLMs how to use something, but thankfully it helped. Here's my tsconfig.json reference sorter:

import { readFile, writeFile } from "node:fs/promises";
import * as jsonc from "jsonc-parser";

const editsOptions = {
  formattingOptions: { tabSize: 2, insertSpaces: true },
};
async function sortReferences(filePath) {
  const contents = await readFile(filePath, "utf8");
  const json = jsonc.parse(contents);

  if (!json.references) {
    return;
  }

  json.references.sort((a, b) => a.path.localeCompare(b.path));

  const edits = jsonc.modify(
    contents,
    ["references"],
    json.references,
    editsOptions,
  );

  const newContents = jsonc.applyEdits(contents, edits);

  if (contents !== newContents) {
    await writeFile(filePath, newContents);
    console.log(`Sorted: ${filePath}`);
  }
}

for (const filePath of process.argv.slice(2)) {
  void sortReferences(filePath).catch((error) => {
    throw new Error(`Error sorting references in ${filePath}`, {
      cause: error,
    });
  });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions