简体   繁体   English

如何将字符串解析为特定的数组字符?

[英]How to parse a String to a specific Array charactere?

In some point, I was able to end this array from my node js server to the navigator page, but it was received as a String so I need to parse it into an array在某些时候,我能够将这个数组从我的节点 js 服务器结束到导航器页面,但它是作为字符串接收的,所以我需要将它解析为一个数组

"['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]"

Is there any tool that can help me to parse it into its array form?是否有任何工具可以帮助我将其解析为数组形式?

You need to replace single quotes to double and wrap the string in brackets for getting an array of arrays.您需要将单引号替换为双引号并将字符串括在括号中以获取数组数组。

 const string = "['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]", array = JSON.parse(`[${string.replace(/'/g, '"')}]`); console.log(array);

Another approach is to use eval , if the data is reliable.如果数据可靠,另一种方法是使用eval

 const string = "['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]", array = eval(`[${string}]`); console.log(array);

If you are forced to use this string, then you have to "make it" looks like JSON, but be aware that this is a very bad idea , you should consider doing something else on your backend in order to send JSON strings to the front end , and not strings with some kind of format.如果你被迫使用这个字符串,那么你必须“让它”看起来像 JSON,但请注意,这是一个非常糟糕的主意,你应该考虑在后端做一些其他的事情,以便将 JSON 字符串发送到前端end ,而不是具有某种格式的字符串。

If you want to risk, you can do something like this:如果你想冒险,你可以这样做:

 let res = JSON.parse('[' + "['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]".replaceAll("'", '"') + ']') console.log(res)

You can use JSON.parse to convert string to array.您可以使用JSON.parse将字符串转换为数组。 Here, pls take care on single quotes.在这里,请注意单引号。 Before using JSON.parse , you need to convert single quotes( ' ) to double quotes ( " ).在使用JSON.parse之前,您需要将单引号 ( ' ) 转换为双引号 ( " )。

 var str = "['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]"; var parsedArray = JSON.parse(`[${str.replaceAll("'", '"')}]`); console.log(parsedArray);

You can use您可以使用

JSON.parse(string);

UPD : I didn't notice that JSON-incompatibile single quotes are used. UPD :我没有注意到使用了 JSON 不兼容的单引号。

I'd propose to just replace them with double quotes:我建议用双引号替换它们:

const jsonCompatString = string.replace(/'/g, `"`);
const serverData = JSON.parse(jsonCompatString);

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

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