简体   繁体   English

如何解析JavaScript中的JSON数组,该数组在数组中的每个对象周围都有一个单引号?

[英]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: 我有一个文本文件,该文件是JSON对象的列表,它们由换行符分隔,如下所示:

{"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 . 我使用fs.readFile(text file)加载该文本文件,然后使用array = data.split("\\n")按行拆分文本文件,然后将每一行插入array ,创建一个名为array的JSON 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. 但是,问题是,当我使用data.split("\\n")分割原始文本文件时,程序将生成的对象在两侧用单引号( ' )括起来,从而导致无效的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? 因此,是否有避免避免添加单引号以使结果成为实际javascript对象的方法? I have attempted to create a for loop and loop through each element in the array and run array[i] = array[i].replace(/'/g, ""); 我试图创建一个for循环,并遍历数组中的每个元素,然后运行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". 您没有“带单引号的JSON”。 You have a list of JSON strings. 您有一个JSON字符串列表。 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" . 推荐阅读,因为我怀疑您正在混淆:Ben Alman的博客- 没有“ JSON Object”之类的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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