Remove trailing commas from JSON with regex

Mar 25, 2019Regex, JSONhttps://git.io/JvE01

Trailing commas are not supported in JSON. Normally you wouldn't come across this issue because you would use JSON serializer directly. However, sometimes you have to construct JSON strings by concatenating substrings on your own.

One common use case can be generating JSON string with templating language such as handlebars or nunjucks where your output data is an object or array whose properties or items are dynamically populated. And here are the situations you need to handle trailing commas:

  • If it's for-loop, you have to check if it's the last item.
  • If it's concatenated by several dynamic segments, you have to check which is the real last item.

Overall it's a hassle to remove the trailing commas in place. So one of the solution can be removing those commas after the templating substitution process with the help of this regular expression:

/,(?!\s*?[{["\w])|(?<=[{[]\s*?),/g

Check out https://regex101.com/r/9qfUGD/1 for test case and detailed explanations.

This regex contains two alternatives, the first one ,(?!\s*?[{["\w]) matches any comma that is not followed by {, [, " or any values, which means the following non-whitespace characters are }. The second one (?<=[{[]\s*?), matches any comma that is following { or [.

Caveat

This is not a perfect solution, as if the commas appear in the strings and are surrounded by brackets, those commas will be matched by the regex and result in false-positive cases. Example: https://regex101.com/r/9qfUGD/2

Powered by Gatsby. Theme inspired by end2end.

© 2014-2020. Made with by mdluo.