[英]Using python, how can I check if a string is a valid json object, even if the string uses single quotes?
Let's say I have a string that looks like this: 假设我有一个看起来像这样的字符串:
"{'apple': 1, 'orange': 2}"
How can I determine if this is a valid json object? 如何确定这是否是有效的json对象? json.loads() doesn't work because the string uses single quotes instead of double.
json.loads()不起作用,因为字符串使用单引号而不是双引号。 Replacing all single quotes with doubles quotes seems risky in the off chance a single quote is escaped, like this:
用单引号引起来替换所有单引号似乎很冒险,因为单引号被转义的可能性很小,如下所示:
"{'sentence':'let\'s solve the issue'}"
Replace all single quotes with double quotes makes the sentence: let"s solve the issue, which is not correct. 用双引号替换所有单引号使句子:让我们解决问题,这是不正确的。
I tried demjson, https://pypi.org/project/demjson/ , and it worked, but it was incredibly slow. 我尝试了demjson, https: //pypi.org/project/demjson/,它可以工作,但是速度非常慢。 Any ideas?
有任何想法吗?
The JSON specification requires objects to have string keys and strings to be double quoted. JSON规范要求对象具有字符串键,并且字符串必须用双引号引起来。
A dict-like object with single quoted fields is not JSON. 具有单引号字段的类似dict的对象不是JSON。
What you have is some other format. 您所拥有的是其他格式。
It could be JSON5 compatible, which allows single quoted strings and has its own JSON5 python library . 它可能与JSON5兼容,从而允许使用单引号引起来的字符串,并具有自己的JSON5 python库 。
It could be a poor JSON implementation, but that should be fixed at the server. 这可能是一个较差的JSON实现,但是应该在服务器上修复。 JSON output is typically implemented with well-tested libraries, and output that is merely JSON-ish is a bad code smell.
JSON输出通常使用经过良好测试的库来实现,而仅仅是JSON-ish的输出是一种不好的代码味道。 It should make a reasonable person wonder what other sloppy code is there.
它应该使一个有理智的人怀疑那里还有其他草率的代码。
As everyone already said (and you found out), if json.loads throws an exception then it isn't a JSON string. 正如大家已经说过的(您发现),如果json.loads引发异常,则它不是JSON字符串。
However, what that happens to be is a valid python dict. 但是,恰好是有效的python字典。 If you're looking into converting it into a JSON string, try this:
如果您想将其转换为JSON字符串,请尝试以下操作:
>>> import json
>>> exec(' '.join(['da_dict =', "{'apple': 1, 'orange': 2}"]))
>>> json.dumps(da_dict)
'{"orange": 2, "apple": 1}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.