0
a1='[{"v1":"value"}, {"v1":"value"}, ]' 
b1=json.loads(a1) 

Creates exceptions, BUT.

a2='[{"v1":"value"}, {"v1":"value"}]' 
b2=json.loads(a2) 

Does not create any exceptions/error. Can someone please help me understand why the last comma in the first example is such a big issue and

how I could still convert the first example without modifying the data?

2
  • 1
    First example is not a valid JSON syntax. You can't parse it with a JSON parser that is compliant with the standard. Quick'n'dirty solution: run it through Python's eval instead of json.loads. Commented Sep 17, 2013 at 4:55
  • You should really ask why is the data in 1 not clean. If you are consuming a webservice why is not sending you proper json etc.. Once you have established that you can look at various methods of cleaning it including the comment above Commented Sep 17, 2013 at 5:44

2 Answers 2

1

JSON syntax does not permit terminal commas, so the parser is correctly rejecting it.

As a side note, this syntax is not valid Javascript either. Some browsers will accept it, but they are acting outside the standard in doing so.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I am getting that type of JSON back from my backend and I just wanted to make sure that I can still work with it. Not sure how I can without actually changing the data (by removing the last comma).
1

It is because your a1 JSON is invalid to being with:

From JSONLint:

Parse error on line 7:
..."value"    },    ]
--------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

The a2 JSON is valid, hence no exception.

EDIT:

Bogdan's 'quick n dirty' solution in the comments will allow you to mute the exception whilst retaining the same code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.