简体   繁体   中英

removing double quote from json.dumps of string data

I have some data that I'm retrieving from a data feed as text. For example, I receive the data like the following:

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

etc.

(This is stock data, where the first column is the timestamp, the next columns are the open, high, low, and close price for the time period.)

I want to convert this into a json such as the following:

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

The code that I'm using is:

  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)

However, when I do this, I'm finding that the values are:

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

Is there anyway for me to get the output without the double quotes?

在输出之前将数据传递给int()float()构造函数,以便将它们转换为数字

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

Change

currentLine = [currentLine[0] , currentLine[1] , currentLine[2], currentLine[3], currentLine[4]]
output.append(currentLine)

to

currentData = map(lambda num: float(num.strip()) , currentLine)
output.append(currentData)

Whenever you initialize currentLine with

currentLine = line.split(",")

all the elements of currentLine are strings. So, whenever you write this to JSON, you get JSON strings throughout. By converting all the strings to numbers, you get something without quotes. Also, I added the strip() calls to handle leading and trailing whitespace as is shown in your data example.

PS Please don't use the same variable name for two completely different things. It's more clear to use currentLine for the list of strings, and currentData for the list of numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM