Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The <a href="https://stackoverflow.com/a/18515363/1639625">answer by @Michael</a> gave me an idea... not a very pretty idea, but it seems to work, at least on your example: Try to parse the JSON string, and if it fails, look for the character where it failed in the exception string<sup>1</sup> and replace that character.</p> <pre><code>while True: try: result = json.loads(s) # try to parse... break # parsing worked -&gt; exit loop except Exception as e: # "Expecting , delimiter: line 34 column 54 (char 1158)" # position of unexpected character after '"' unexp = int(re.findall(r'\(char (\d+)\)', str(e))[0]) # position of unescaped '"' before that unesc = s.rfind(r'"', 0, unexp) s = s[:unesc] + r'\"' + s[unesc+1:] # position of correspondig closing '"' (+2 for inserted '\') closg = s.find(r'"', unesc + 2) s = s[:closg] + r'\"' + s[closg+1:] print result </code></pre> <p>You may want to add some additional checks to prevent this from ending in an infinite loop (e.g., at max as many repetitions as there are characters in the string). <strike>Also, this will still not work if an incorrect <code>"</code> is actually followed by a comma, as pointed out by @gnibbler.</strike></p> <p><strong>Update:</strong> This seems to work <em>pretty</em> well now (though still not perfect), even if the unescaped <code>"</code> is followed by a comma, or closing bracket, as in this case it will likely get a complaint about a syntax error after that (expected property name, etc.) and trace back to the last <code>"</code>. It also automatically escapes the corresponding closing <code>"</code> (assuming there is one).</p> <hr> <p><sup>1)</sup> The exception's <code>str</code> is <code>"Expecting , delimiter: line XXX column YYY (char ZZZ)"</code>, where ZZZ is the position in the string where the error occurred. Note, though, that this message may depend on the version of Python, the <code>json</code> module, the OS, or the locale, and thus this solution may have to be adapted accordingly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload