Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can json.loads ignore trailing commas?

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?

like image 894
Rob Watts Avatar asked May 16 '14 22:05

Rob Watts


People also ask

Are trailing commas forbidden in JSON?

As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON.

How do you escape a comma in JSON?

Hold an int (without commas) and then format the output of this int to include commas, when you output it.

How do I remove the last comma from a JSON string in Python?

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.

What does a comma mean in JSON?

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.


1 Answers

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 
like image 162
andrewgrz Avatar answered Oct 13 '22 02:10

andrewgrz