我有一些数据是以文本的形式从数据馈送中检索的。例如,我接收的数据如下:
1105488000000, 34.1300, 34.5750, 32.0700, 32.2800\r\n
1105574400000, 32.6750, 32.9500, 31.6500, 32.7300\r\n
1105660800000, 36.8250, 37.2100, 34.8650, 34.9000\r\n等。
(这是股票数据,其中第一列是时间戳,下一列是该时间段的开盘价、高价、低价和收盘价。)
我想将其转换为如下所示的json:
[
[1105488000000, 34.1300, 34.5750, 32.0700, 32.2800],
[1105574400000, 32.6750, 32.9500, 31.6500, 32.7300],
[1105660800000, 36.8250, 37.2100, 34.8650, 34.9000],
...我使用的代码是:
lines = data.split("\r\n");
output = []
for line in lines:
currentLine = line.split(",")
currentLine = [currentLine[0] , currentLine[1] , currentLine[2], currentLine[3], currentLine[4]]
output.append(currentLine)
jsonOutput = json.dumps(output)然而,当我这样做时,我发现这些值是:
[
["1105488000000", "34.1300", "34.5750", "32.0700", "32.2800"],
["1105574400000", "32.6750", "32.9500", "31.6500", "32.7300"],
["1105660800000", "36.8250", "37.2100", "34.8650", "34.9000"],有没有办法让我在没有双引号的情况下得到输出?
发布于 2012-03-06 10:11:05
在输出之前通过int()或float()构造函数传递数据,以便将它们转换为numbers。
发布于 2012-03-06 10:14:20
...
currentLine = [float(i) for i in currentLine]
output.append(currentLine)
...发布于 2012-03-06 10:10:37
变化
currentLine = [currentLine[0] , currentLine[1] , currentLine[2], currentLine[3], currentLine[4]]
output.append(currentLine)至
currentData = map(lambda num: float(num.strip()) , currentLine)
output.append(currentData)无论何时使用初始化currentLine
currentLine = line.split(",")currentLine的所有元素都是字符串。因此,无论何时将此代码写入JSON,都会始终获得JSON字符串。通过将所有字符串转换为数字,您可以获得不带引号的内容。另外,我添加了strip()调用来处理前导空格和尾随空格,如您的数据示例所示。
附注:请不要为两个完全不同的东西使用相同的变量名。对于字符串列表使用currentLine,对于数字列表使用currentData会更清楚。
https://stackoverflow.com/questions/9576954
复制相似问题