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.
Why do I get square brackets when trying to convert array to JSON string using stringify
convert string with square brackets to array or list in Javascript - Stack Overflow
Why array toString() removes the square bracket? It is especially ugly with nested arrays.
javascript convert string into array of int with brackets - Stack Overflow
You are using an Array as an object.
In Javascript you have Arrays and objects. But as you may know Arrays are also objects and this has some weird implications.
var arr = [];
arr[0] = "foo"; // this is fine
console.log(JSON.stringify(arr)); // [ "foo" ]
arr.length; // 1 ok
But since an Array is an object, we can also assign properties:
arr.foo = "bar";
console.log(arr); // [ 0: "foo", foo: "bar" ]
console.log(JSON.stringify(arr)); // [ "foo" ] .. where did bar go?
arr.length; // 1 huh?
We're mixing array values and object properties.
The JSON encoder looks at the object and sees that it's an (instanceof) Array and serializes it. It looks at arr.length (which is 1 in the example) so you get just [ "foo" ]. The properties on the array are ignored.
It's important to realize the difference between array valus and object properties. Arrays in JavaScript are never associative. If you set a property on an Array it wont increase the length and it wont show up if you loop over it in a for-loop.
Change:
var shipInfo = new Array();
To:
var shipInfo = {};
shipInfo is not an array, it is an object so try var shipInfo = {};
Demo: Problem, Solution
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
I know that I can workaround it by calling JSON.stringify.
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, '')