Displaying better error message than “No JSON object could be decoded”

后端 未结 11 1083
既然无缘
既然无缘 2020-11-30 23:05

Python code to load data from some long complicated JSON file:

with open(filename, \"r\") as f:
  data = json.loads(f.read())

(note: the be

11条回答
  •  盖世英雄少女心
    2020-11-30 23:43

    I've found that the simplejson module gives more descriptive errors in many cases where the built-in json module is vague. For instance, for the case of having a comma after the last item in a list:

    json.loads('[1,2,]')
    ....
    ValueError: No JSON object could be decoded
    

    which is not very descriptive. The same operation with simplejson:

    simplejson.loads('[1,2,]')
    ...
    simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)
    

    Much better! Likewise for other common errors like capitalizing True.

提交回复
热议问题