Use JSON.stringify():
var x = document.getElementById("result");
x.textContent = JSON.stringify( myArray );
Answer from Sirko on Stack OverflowUse JSON.stringify():
var x = document.getElementById("result");
x.textContent = JSON.stringify( myArray );
You can either use JSON.stringify or custom joining like this
console.log("[[" + myArray.join("],[") + "]]");
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
console.log(JSON.stringify(myArray));
# [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
Use JSON.stringify
JSON.stringify(fruits)
in order to do that you'll need to iterate through the array and build the string from scratch.
so something like this:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
// first make sure that each fruit is between quotes
var fruitsResult = fruits.map(function(fruit) {
return '"' + fruit + '"';
});
// join the fruits with the comma's in between
var result = fruitsResult.join(', ');
// add the final brackets around it
result = '[' + result + ']'
This is a basic solution that you can either add as a single function somewhere and pass the array to our you can extend the Array prototype with your own method so you can call fruits.toMyStringFunction(). It's up to you how you want to implement this.
Note: that I'm using the Array.prototype.map() method that is supported in modern browsers but will cause some issues with IE8 and lower. This step can also be done using a for loop but this is more elegant.
It seems like you can write a pretty straightforward parser:
const parse = (str) => {
let depth = 0;
let item = '';
let items = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '[') {
depth++;
if (depth === 2) {
items.push([]);
}
}
else if (str[i] === ']') {
if (depth === 3) {
items[items.length - 1].push(item);
item = '';
}
depth--;
}
else if (depth === 3) {
item += str[i]
}
}
return items;
}
console.log(parse("[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]"));
console.log(parse("[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]"))
function parse(s) {
return JSON.parse(s
.replace(/(?<=\[)([^\[\]])/g, "\"$1")
.replace(/([^\[\]])(?=\])/g, "$1\""));
}
const s1 = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]";
console.log(parse(s1));
const s2 = "[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]";
console.log(parse(s2));
Here is how the regexes work:
- A quotation mark is put before every character that is not a bracket, but follows an opening bracket (checked using positive lookbehind).
- A quotation mark is put after every character that is not a bracket, but precedes a closing bracket (checked using positive lookahead).
This way everything inside brackets is wrapped into strings and the bracket structure can be parsed into an Array hierarchy using JSON.parse.
IMPORTANT: If you'd also want to run the functions in the strings, and this code runs in the browser, do not use eval! Use a Web Worker instead, which runs in a separate context (here is how).
UPDATE
The code can be simplified to use a single replace:
function parse(s) {
return JSON.parse(s.replace(/(?<=\[)([^\[\]]+)(?=\])/g, "\"$1\""));
}
const s1 = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]";
console.log(parse(s1));
const s2 = "[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]";
console.log(parse(s2));
Although this version is simpler and faster, it's still much slower than @Dave's parser: https://jsperf.com/https-stackoverflow-com-questions-63048607
JSON.stringify(dataArray) will always return square brackets because dataArray is of type array. Instead, you could stringify each element of your array, then join them separated by commas.
dataArray = dataArray.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
Then
["newData",4,2]
becomes
"newData",4,2
Addendum: Please don't try to replace() out the brackets manually because it could be that one day a bracket enters your array in a string. e.g. ["Please see ref[1]",4,2]
Thanks Drakes and S McCrohan for your answers. I found that .replace(/]|[[]/g, '') appended to JSON.stringify(dataArray)
full line JSON.stringify(dataArray).replace(/]|[[]/g, '')