Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Unescape JSON5 identifier values #165

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions js/src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,20 @@ const DEFAULT_OPTIONS = {
allowTrailingCommas: false
};

const UNICODE_SEQUENCE = /\\u[\da-z]{4}/gu;

/**
* Normalizes a JSON5 identifier by converting Unicode escape sequences into
* their corresponding characters.
* @param {string} identifier The identifier to normalize.
* @returns {string} The normalized identifier.
*/
function normalizeIdentifier(identifier) {
return identifier.replace(UNICODE_SEQUENCE, unicodeEscape => {
return String.fromCharCode(parseInt(unicodeEscape.slice(2), 16));
});
}

/**
* Converts a JSON-encoded string into a JavaScript string, interpreting each
* escape sequence.
Expand Down Expand Up @@ -358,8 +372,7 @@ export function parse(text, options) {
// check if the token is NaN or Infinity
return t[identifier.includes("NaN") ? "nan" : "infinity"](/** @type {Sign} */ (sign), parts);
}

return t.identifier(identifier, parts);
return t.identifier(normalizeIdentifier(identifier), parts);
}

/**
Expand Down
7 changes: 7 additions & 0 deletions js/tests/parse.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,13 @@ describe("parse()", () => {
const result = parse(text, { mode: "json5" });
expect(result.body.value).to.equal(1);
});

it("should unescape unquoted property names", () => {
const text = "{ f\\u006fo: 1 }";
const expected = json5.parse(text);
const result = parse(text, { mode: "json5" });
expect(result.body.members[0].name.name).to.equal(Object.keys(expected)[0]);
});
});

describe("fixtures", () => {
Expand Down
Loading