Skip to content

Commit

Permalink
fix: Unescape JSON5 identifier values (#165)
Browse files Browse the repository at this point in the history
fixes #164
  • Loading branch information
nzakas authored Dec 3, 2024
1 parent 0382b39 commit 5633bc4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
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

0 comments on commit 5633bc4

Please sign in to comment.