As mentioned in this StackOverflow question, you are not allowed to have any trailing commas in json. For example, this
{ "key1": "value1", "key2": "value2" }
is fine, but this
{ "key1": "value1", "key2": "value2", }
is invalid syntax.
For reasons mentioned in this other StackOverflow question, using a trailing comma is legal (and perhaps encouraged?) in Python code. I am working with both Python and JSON, so I would love to be able to be consistent across both types of files. Is there a way to have json.loads
ignore trailing commas?
As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON.
Hold an int (without commas) and then format the output of this int to include commas, when you output it.
If your JSON is valid except for the trailing commas, you can try using more relaxed parsers like the other solution said. If you just want to remove the trailing commas, this regex should work. Replace all occurrences with an empty string.
An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas. array = begin-array [ value *( value-separator value ) ] end-array.
Strip the commas before you pass the value in.
import re def clean_json(string): string = re.sub(",[ \t\r\n]+}", "}", string) string = re.sub(",[ \t\r\n]+\]", "]", string) return string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With