简体   繁体   中英

How to parse a JSON array in javascript that has a single quote around each object in the array?

I have a weird situation here. I have a text file that is a list of JSON objects and they are separated by line breaks like this:

{"upSpeed": 13.860419184316857, "downSpeed": 85.93058668830014, "time": "2016-12-12T21:31:56.507318"}
{"upSpeed": 13.860419184316857, "downSpeed": 85.93058668830014, "time": "2016-12-12T21:31:56.507318"}
{"upSpeed": 13.890492898595365, "downSpeed": 87.35392034236816, "time": "2016-12-12T21:37:52.174878"}
{"upSpeed": 13.69741910903317, "downSpeed": 88.08812682966898, "time": "2016-12-12T21:41:04.688231"}
...

I use fs.readFile(text file) to load that text file and then array = data.split("\\n") to split the text file by line and then insert each line into array , creating a JSON array named array . But, the issue is when I split the original text file using data.split("\\n") , the program wraps the resulting object in single quotes ( ' ) on either side, resulting in invalid JSON. So, it ends up looking like this:

[ '{"upSpeed": 13.860419184316857, "downSpeed": 85.93058668830014, "time": "2016-12-12T21:31:56.507318"}',
  '{"upSpeed": 13.860419184316857, "downSpeed": 85.93058668830014, "time": "2016-12-12T21:31:56.507318"}',
  '{"upSpeed": 13.890492898595365, "downSpeed": 87.35392034236816, "time": "2016-12-12T21:37:52.174878"}',
  '{"upSpeed": 13.69741910903317, "downSpeed": 88.08812682966898, "time": "2016-12-12T21:41:04.688231"}'
...]

So, is there anyway to avoid the single quotes from being added in so the result is an actual javascript object? I have attempted to create a for loop and loop through each element in the array and run array[i] = array[i].replace(/'/g, ""); to replace the single quotes with nothing ( "" ) but that simply does not work and returns the same exact result shown above. Any ideas?

You don't have "JSON with single quotes". You have a list of JSON strings. The single quotes are just node's way of writing that to the console.

Just parse each of them individually.

var items = data.split(/\n/).map(JSON.parse);

Recommended reading, because I suspect you are mixing up things: Ben Alman's blog - There's no such thing as a "JSON Object" .

您是否尝试过类似的方法: var jsonItem = JSON.parse(array[i]);

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