2012-03-06 147 views
1

我有一些数据是从数据馈送中作为文本检索的。例如,收到的数据如下所示:从json.dumps的字符串数据中删除双引号

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

反正对我来说,得到的输出没有双引号?

+0

这是因为您将字符串插入到数组中而不是插入数字。 – 2012-03-06 02:28:53

回答

3

以便把它们变成号码输出之前通过所述int()float()构造的数据。

+0

谢谢。我试过了,并且我的结果有小数点问题,例如: [1105488000000,34.130000000000003,34.579999999999998,32.07,32.280000000000001] 我试过使用round,但是这似乎不起作用。我搜索了十进制,但json似乎无法序列化十进制。 – steve8918 2012-03-06 02:23:00

+0

是的,欢迎来到IEEE 754浮点数,那里只有很少的确切值。 – 2012-03-06 02:24:47

+0

我有其他的选择吗?或者JSON库不适合我,我必须自己构建JSON? – steve8918 2012-03-06 02:29:46

2

变化

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()调用来处理数据示例中显示的前导空白和尾随空白。

P.S.请不要为两个完全不同的东西使用相同的变量名称。使用currentLine作为字符串列表更清晰,数字列表使用currentData

+1

['map'](http://docs.python.org/tutorial/datastructures.html#functional-programming-tools)在这里可能非常有用。 – sarnold 2012-03-06 02:12:43

+0

@sarnold map也是我的第一本能,但是我对使用map的时候非常谨慎,只要我的输出数据必须有一定的大小,但是我的输入数据可能更大。也就是说,问题中的数据样本每行总是5个数字,所以我修改了使用map的答案。 – 2012-03-06 02:18:45

+0

heh,[kev's answer](http://stackoverflow.com/a/9577022/377270)仍然更清洁;在列表推导被引入之前,我主要使用Python,所以它们仍然在我的脑海中。 – sarnold 2012-03-06 02:20:05

3
... 
currentLine = [float(i) for i in currentLine] 
output.append(currentLine) 
...