Since array literal notation is still valid JSON, you can use JSON.parse() to convert that string into an array, and from there, use it's values.

Use with AIvar test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]

//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
Answer from Joseph on Stack Overflow
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ jquery create array from string
jQuery Create Array From String โ€” SitePoint
February 12, 2024 - You can use the split() method to convert the string into an array and then use the reverse() method to reverse the order of the elements.
๐ŸŒ
SitePoint
sitepoint.com โ€บ blog โ€บ javascript โ€บ jquery convert json string to array
jquery convert json string to array โ€” SitePoint
February 12, 2024 - Simple jQuery snippet to convert JSON string to an array of objects and then interate output of thier values.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 33384410 โ€บ jquery-convert-string-to-array
javascript - Jquery - Convert string to Array - Stack Overflow
How to convert this string to an Array? javascript ยท jquery ยท arrays ยท Share ยท Improve this question ยท Follow ยท edited Oct 28, 2015 at 6:37 ยท asked Oct 28, 2015 at 6:35 ยท Anup ยท 9,7741717 gold badges7777 silver badges149149 bronze badges 16 ยท 1 ยท JSON.parse(data); ignoring the errors ยท
๐ŸŒ
jQuery
api.jquery.com โ€บ jQuery.makeArray
jQuery.makeArray() | jQuery API Documentation
Description: Convert an array-like object into a true JavaScript array. ... Any object to turn into a native Array.
Find elsewhere
Top answer
1 of 7
84

I think that the best way of doing this, as Douglas Crockford (one of the biggests gurus of JavaScript) suggests in here is using the JSON native parser, as it is not only faster than the eval(), it's also more secure.

Native JSON parser is already available in:

  • Firefox 3.5+
  • IE 8+
  • Opera 10.5+
  • Safari Safari 4.0.3+
  • Chrome (don't know which version)

And Crockford has made a safe fallback in javascript, called json2.js, which is an adaption of the eval() approach, with some security bits added and with the native JSON parsers API. You just need to include that file, remove its first line, and use the native JSON parser, and if it's not present json2 would do the work.

Here is an example:

var myJSONString = '{ "a": 1, "b": 2 }',
    myObject = JSON.parse(myJSONString);

Once parsed you'll get an object with attributes a and b, and as you may know, you can treat an object as a hash table or associative array in JavaScript, so you would be able to access the values like this:

myObject['a'];

If you just want a simple array and not an associative one you could do something like:

var myArray = [];
for(var i in myObject) {
    myArray.push(myObject[i]);
}

Lastly, although not necessary in plain JavaScript, the JSON spec requires double quoting the key of the members. So the navite parser won't work without it. If I were you I would add it, but if it is not possible use the var myObject = eval( "(" + myString + ")" ); approach.

2 of 7
10

Since your string is malformed JSON, a JSON parser can't parse it properly and even eval() will throw an error. It's also not an Array but a HashMap or simply an Object literal (malformed). If the Object literal will only contain number and string values (and no child objects/arrays) you can use the following code.

function malformedJSON2Array (tar) {
    var arr = [];
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        arr[i] = {};
        pair = cur.split(':');
        arr[i][pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return arr;
}

malformedJSON2Array("{a:12, b:c, foo:bar}");
// result -> [{a:12},{b:'c'},{foo:'bar'}]

That code will turn your string into an Array of Objects (plural).

If however you actually wanted a HashMap (Associative Array) and NOT an array, use the following code:

function malformedJSON2Object(tar) {
    var obj = {};
    tar = tar.replace(/^\{|\}$/g,'').split(',');
    for(var i=0,cur,pair;cur=tar[i];i++){
        pair = cur.split(':');
        obj[pair[0]] = /^\d*$/.test(pair[1]) ? +pair[1] : pair[1];
    }
    return obj;
}

malformedJSON2Object("{a:12, b:c, foo:bar}");
// result -> {a:12,b:'c',foo:'bar'}

The above code will become a lot more complex when you start nesting objects and arrays. Basically you'd have to rewrite JSON.js and JSON2.js to support malformed JSON.

Also consider the following option, which is still bad I admit, but marginally better then sticking JSON inside an HTML tag's attribute.

<div id="DATA001">bla</div>
<!-- namespacing your data is even better! -->
<script>var DATA001 = {a:12,b:"c",foo:"bar"};</script>

I am assuming you omit quote marks in the string because you had put it inside an HTML tag's attribute and didn't want to escape quotes.

๐ŸŒ
Aspdotnet-suresh
aspdotnet-suresh.com โ€บ 2015 โ€บ 03 โ€บ jquery-split-string-into-array-by-comma-split-comma-separated-string-into-array.html
jQuery Split String into Array by Comma or jQuery Split Comma Separated String into Array - ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview
To split string into array by comma we can use split() function in jQuery for that we need to write the code like as shown below ยท If you want to check it in complete example you need to write the code like as shown below ... For live demo enter text in textbox with comma separated and check ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 22798871
javascript - String to Array JQuery - Stack Overflow
1 String to array and take individual value in jquery ยท 0 jQuery Convert string of values to array ยท 2 convert array stored in a string to an array ยท 0 convert string array into array of strings ยท Has anyone else made this definition of a "finitely bounded" set of finite sets?
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 31747913 โ€บ convert-string-into-array-using-regular-expression-in-jquery-javascript
Convert string into array using regular expression in jquery, javascript - Stack Overflow
May 23, 2017 - I would like to split string into array as bellow <script> var str='strat with any string[A][/A][X][/X]test string[C][/C]End with any string[C][/C]'; var arr== ["strat with any string", "[A][/A]", "[X][/X]", "test string", "[C][/C]", "End with any string", "[C][/C]"]; </script>
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_split.asp
JavaScript String split() Method
The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words. ... Coding fundamentals as bite-sized lessons and challenges.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-convert-list-of-elements-in-an-array-using-jquery
How to Convert List of Elements in an Array using jQuery? - GeeksforGeeks
October 8, 2024 - Take the text value of each child and append that to the array. Example 1: This example uses .each() method to convert a list of elements in an array.
๐ŸŒ
SitePoint
sitepoint.com โ€บ javascript
jQuery - Convert String to Javascript Array - JavaScript - SitePoint Forums | Web Development & Design Community
January 19, 2011 - var string = "[[1088163336,80],[1088154636,95],[1088150436,75]]" var arrayLit = string; if(eval(arrayLit).length > 1){ //Some Stuff } Thanks for any suggestions you may be able to offer. ... It turns out the actual problem is illformated strings. Iโ€™m trying to create a regex to replace all characters in the string which are not: numeric, brackets, commas, or decimals.