将包含python列表的字符串转换为列表的安全方法

时间:2013-05-07 07:17:54

标签: python string security list parsing

使用HTTP查询我得到像这样的数据(作为字符串)

[[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]]

假设我们将数据存储在名为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]]"

我想获得一个包含数据的列表lst

我的第一个想法是做

lst = eval(s)

所以我得到了:

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]]

但我不喜欢这个...因为 不安全

如果网站返回类似

的内容
os.system('rm / -rf')

这可能是灾难性的!!!

所以我正在寻找一种安全的方法将包含python列表的字符串转换为python列表。

1 个答案:

答案 0 :(得分:8)

import ast
ast.literal_eval(data)

或者您可以使用json.load直接从查询加载,如果它是一个类似对象的文件(如果可以的话,尝试直接从文件加载)或json.loads如果它是#sa串

import json
json.loads(query)