0

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?

5
  • Is it assumed that all single quotes are escaped if they are a part of a string? Commented Feb 10, 2019 at 2:00
  • 7
    Fix whatever program is generating the string to generate valid JSON instead. Commented Feb 10, 2019 at 2:01
  • Replace all single quotes with double quotes makes the sentence: let"s solve the issue, which is not correct. But does it successfully parse as json? If so, then you've answered the question. Commented Feb 10, 2019 at 2:04
  • 2
    You've already determined that it's not a valid JSON object. Commented Feb 10, 2019 at 2:04
  • 4
    "how can I check if a string is a valid json" - if json.loads() throws an exception it's not valid JSON. Simple as that. Commented Feb 10, 2019 at 2:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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}'

1 Comment

Don't use exec to create a variable like that! This is what ast.literal_eval was made for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.