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

Bug in the JSON parser with JavaScript code #30

Open
josdejong opened this issue Oct 1, 2022 · 0 comments
Open

Bug in the JSON parser with JavaScript code #30

josdejong opened this issue Oct 1, 2022 · 0 comments

Comments

@josdejong
Copy link

First, thanks for the excellent article JSON Parser with JavaScript. I like the straightforward and easy to understand code, and it was faster than my original code. I used it as a basis to simplify and improve my own lossless-json parser , the parse code in v2 code is largely yours 😄 .

The full CodeSandbox example in the article contains a bug though when parsing escaped control characters like \n and \t (line 100-111). These are replaced with regular word characters n and t instead of the real control characters:

        if (str[i] === "\\") {
          const char = str[i + 1];
          if (
            char === '"' ||
            char === "\\" ||
            char === "/" ||
            char === "b" ||
            char === "f" ||
            char === "n" ||
            char === "r" ||
            char === "t"
          ) {
            result += char; // Oops! Here we should append the real control character
            i++;
          }

In lossless-json I solved this by having a map escapeCharacters and using the value from the map, holding the real control characters, see code:

        if (text[i] === '\\') {
          const char = text[i + 1]
          const escapeChar = escapeCharacters[char]
          if (escapeChar !== undefined) {
            result += escapeChar
            i++
const escapeCharacters = {
  '"': '"',
  '\\': '\\',
  '/': '/',
  b: '\b',
  f: '\f',
  n: '\n',
  r: '\r',
  t: '\t'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant