Why search-and-replace is the wrong way to fix a trailing comma in JSON
A single comma can make a whole JSON file unusable: { "name" : "ada" , "roles" : [ "admin" , "ops" ,], } # Python json.decoder.JSONDecodeError: Expecting value: line 3 column 28 (char 46) # Node / Chrome SyntaxError: Unexpected token ']', ..."n", "ops",], }" is not valid JSON Both parsers stop at the first problem, the comma inside the array. Fix that one, and the comma before the final } fails…
The comma at the end of a JSON file can cause it to become unusable. For example, { name : ada , roles : [ admin , ops], } results in a Python json.decoder.JSONDecodeError or Node SyntaxError. JSON syntax does not allow trailing commas, so the parser stops at the first problem.
The one-liner fix, re.sub(r ',\s*([}\]]) , r '\1', text), works for simple cases. However, it can corrupt values inside strings, like changing the value of note from "ends with ," to "ends with } " when applied to a string containing commas.
To remove trailing commas correctly, you must track whether you are inside a string and watch for backslash escapes. A proper solution would be to use a function like remove_trailing_commas(text: str) -> str, which appends characters to a list while tracking string and escape state. It removes the comma only if it is outside a string and the next non-whitespace character closes an object or array.
In summary, repair only trailing commas outside strings, as they have a single defensible fix. Fail loudly with a line and column for other issues. This approach ensures the integrity of the JSON data.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.