Python无法使用额外的结尾逗号来解析JSON [英] Python can't parse JSON with extra trailing comma

查看:394
本文介绍了Python无法使用额外的结尾逗号来解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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

在Python 2中产生此错误:

produces this error in Python 2:

ValueError:期望的属性名称:第1行第16列(字符15)

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

Python 3的类似结果

Similar result in Python 3:

json.decoder.JSONDecodeError:期望属性名称用双引号引起来:第1行第16列(字符15)

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

如果我删除了结尾的逗号(在"value2"之后),则不会出现任何错误.但是我的代码将处理许多不同的JSON,因此无法手动执行.是否可以将解析器设置为忽略这些最后的逗号?

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?

推荐答案

JSON规范不允许尾随逗号.解析器抛出异常,因为它遇到无效的语法标记.

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

您可能会对这些文件使用其他解析器感兴趣,例如.为 JSON5规范构建的解析器,它允许这种语法.

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

这篇关于Python无法使用额外的结尾逗号来解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆