简体   繁体   中英

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.loads() doesn't work because the string uses single quotes instead of double. 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. Any ideas?

The JSON specification requires objects to have string keys and strings to be double quoted.

A dict-like object with single quoted fields is not 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 .

It could be a poor JSON implementation, but that should be fixed at the server. JSON output is typically implemented with well-tested libraries, and output that is merely JSON-ish is a bad code smell. 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.

However, what that happens to be is a valid python dict. If you're looking into converting it into a JSON string, try this:

>>> import json
>>> exec(' '.join(['da_dict =', "{'apple': 1, 'orange': 2}"]))
>>> json.dumps(da_dict)
'{"orange": 2, "apple": 1}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM