Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python can't parse JSON with extra trailing comma

This code:

import json
s = '{ "key1": "value1", "key2": "value2", }'
json.loads(s)

produces this error in Python 2:

ValueError: Expecting property name: line 1 column 16 (char 15)

Similar result in Python 3:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 16 (char 15)

If I remove that trailing comma (after "value2"), I get no error. But my code will process many different JSONs, so I can't do it manually. Is it possible to setup the parser to ignore such last commas?

like image 730
AivanF. Avatar asked Oct 03 '18 23:10

AivanF.


2 Answers

Another option is to parse it as YAML; YAML accepts valid JSON but also accepts all sorts of variations.

import yaml
s = '{ "key1": "value1", "key2": "value2", }'
yaml.load(s)
like image 133
jnnnnn Avatar answered Sep 24 '22 04:09

jnnnnn


JSON specification doesn't allow trailing comma. The parser is throwing since it encounters invalid syntax token.

You might be interested in using a different parser for those files, eg. a parser built for JSON5 spec which allows such syntax.

like image 24
Lazar Ljubenović Avatar answered Sep 20 '22 04:09

Lazar Ljubenović