Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If your format really is just one or more <code>var foo = [JSON array or object literal];</code>, you can just write a dotall regex to extract them, then parse each one as JSON. For example:</p> <pre><code>&gt;&gt;&gt; j = '''var line1= [["Wed, 12 Jun 2013 01:00:00 +0000",22.4916114807,"2 sold"], ["Fri, 14 Jun 2013 01:00:00 +0000",27.4950008392,"2 sold"], ["Sun, 16 Jun 2013 01:00:00 +0000",19.5499992371,"1 sold"], ["Tue, 18 Jun 2013 01:00:00 +0000",17.25,"1 sold"], ["Sun, 23 Jun 2013 01:00:00 +0000",15.5420341492,"2 sold"], ["Thu, 27 Jun 2013 01:00:00 +0000",8.79045295715,"3 sold"], ["Fri, 28 Jun 2013 01:00:00 +0000",10,"1 sold"]];\s*$''' &gt;&gt;&gt; values = re.findall(r'var.*?=\s*(.*?);', j, re.DOTALL | re.MULTILINE) &gt;&gt;&gt; for value in values: ... print(json.loads(value)) [[['Wed, 12 Jun 2013 01:00:00 +0000', 22.4916114807, '2 sold'], ['Fri, 14 Jun 2013 01:00:00 +0000', 27.4950008392, '2 sold'], ['Sun, 16 Jun 2013 01:00:00 +0000', 19.5499992371, '1 sold'], ['Tue, 18 Jun 2013 01:00:00 +0000', 17.25, '1 sold'], ['Sun, 23 Jun 2013 01:00:00 +0000', 15.5420341492, '2 sold'], ['Thu, 27 Jun 2013 01:00:00 +0000', 8.79045295715, '3 sold'], ['Fri, 28 Jun 2013 01:00:00 +0000', 10, '1 sold']]] </code></pre> <p>Of course this makes a few assumptions:</p> <ul> <li>A semicolon at the end of the line must be an actual statement separator, not the middle of a string. This should be safe because JS doesn't have Python-style multiline strings.</li> <li>The code actually does have semicolons at the end of each statement, even though they're optional in JS. Most JS code has those semicolons, but it obviously isn't guaranteed.</li> <li>The array and object literals really are JSON-compatible. This definitely isn't guaranteed; for example, JS can use single-quoted strings, but JSON can't. But it does work for your example.</li> <li>Your format really is this well-defined. For example, if there might be a statement like <code>var line2 = [[1]] + line1;</code> in the middle of your code, it's going to cause problems.</li> </ul> <p>Note that if the data might contain JavaScript literals that aren't all valid JSON, but are all valid Python literals (which isn't likely, but isn't impossible, either), you can use <code>ast.literal_eval</code> on them instead of <code>json.loads</code>. But I wouldn't do that unless you know this is the case.</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