0

Using an HTTP query I get data (as string) like this

[[1356912000, 13.391120000000, 13.509900000000, 13.391120000000, 13.509320000000, 41.088424560000, 555.033691727713, 13.508273867187],
 [1356912900, 13.509320000000, 13.549990000000, 13.424280000000, 13.424420000000, 65.617187260000, 887.084786010319, 13.519091918636],
 ... ,
 [1359589500, 19.750000000000, 19.783450000000, 19.700000000000, 19.700010000000, 171.512197650000, 3389.270172356359, 19.761102818312],
 [1359590400, 19.700010000000, 19.783450000000, 19.700000000000, 19.700010000000, 161.142525670000, 3183.651205816806, 19.756741385179]]

Let's say that we have data stored in a string named s

s = "[[1356912000, 13.391120000000, 13.509900000000, 13.391120000000, 13.509320000000, 41.088424560000, 555.033691727713, 13.508273867187], [1356912900, 13.509320000000, 13.549990000000, 13.424280000000, 13.424420000000, 65.617187260000, 887.084786010319, 13.519091918636], [1359589500, 19.750000000000, 19.783450000000, 19.700000000000, 19.700010000000, 171.512197650000, 3389.270172356359, 19.761102818312], [1359590400, 19.700010000000, 19.783450000000, 19.700000000000, 19.700010000000, 161.142525670000, 3183.651205816806, 19.756741385179]]"

I want to get a list lst containing data

My first idea was to do

lst = eval(s)

So I get:

In [10]: lst
Out[10]: 
[[1356912000,
  13.39112,
  13.5099,
  13.39112,
  13.50932,
  41.08842456,
  555.033691727713,
  13.508273867187],
 [1356912900,
  13.50932,
  13.54999,
  13.42428,
  13.42442,
  65.61718726,
  887.084786010319,
  13.519091918636],
 [1359589500,
  19.75,
  19.78345,
  19.7,
  19.70001,
  171.51219765,
  3389.270172356359,
  19.761102818312],
 [1359590400,
  19.70001,
  19.78345,
  19.7,
  19.70001,
  161.14252567,
  3183.651205816806,
  19.756741385179]]

But I don't like this... because that's unsafe.

If website returns something like

os.system('rm / -rf')

it could be disastrous!!!

So I'm looking for a safe way to convert a string which contains a python list to a python list.

working4coins
  • 1,997
  • 3
  • 22
  • 30

1 Answers1

8
import ast
ast.literal_eval(data)

Or you could load straight from the query using json.load if it's a file like object (try to load straight from the file if you can) or json.loads if it's a string

import json
json.loads(query)
jamylak
  • 128,818
  • 30
  • 231
  • 230