Remove trailing commas from JSON with regex

25 Mar, 2019Regex, JSON

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:


Check out 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 [.


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:

Powered by Gatsby. Theme inspired by end2end.

© 2014-2022. Made withby mdluo.