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.

Answer from alcuadrado on Stack Overflow
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-basics-strings-arrays-objects
JavaScript Basics โ€“ How to Work with Strings, Arrays, and Objects in JS
March 20, 2023 - It follows a prototype-based model, but it also offers a class syntax to enable typical OOP paradigms. In JavaScript, strings and arrays are objects, and every object in JavaScript is a template which has its methods and properties.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ String
String - JavaScript - MDN Web Docs
May 22, 2026 - There are two ways to access an individual character in a string. The first is the charAt() method: ... The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-convert-string-to-array-of-objects-javascript
How to Convert String to Array of Objects JavaScript ? - GeeksforGeeks
August 5, 2025 - Example: Converting String Records to Array of Objects it involves splitting a string of records, mapping each record to an object with name and age properties, and then logging the resulting array of objects.
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.

๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ article โ€บ array-and-string-object-in-javascript
String Objects in JavaScript
March 17, 2023 - JavaScript String Object is a universal object that is used to store strings.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_arrays.asp
JavaScript Arrays
Arrays are a special kind of objects, with numbered indexes. JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text).
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-convert-string-of-objects-to-array-in-javascript
How to Convert String of Objects to Array in JavaScript ? - GeeksforGeeks
July 23, 2025 - The most common and straightforward way to convert a string of objects to an array of objects is by using JSON.parse() method. This method parses a JSON string into a JavaScript object or array.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array
Array - JavaScript - MDN Web Docs
2 days ago - (When those characteristics are undesirable, use typed arrays instead.) JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
๐ŸŒ
xjavascript
xjavascript.com โ€บ blog โ€บ best-way-to-convert-string-to-array-of-object-in-javascript
Best Ways to Convert a String to an Array of Objects in JavaScript: A Practical Guide โ€” xjavascript.com
If your string is a valid JSON array of objects, JSON.parse() is the simplest and most efficient solution. JSON (JavaScript Object Notation) is a standard data format, so APIs, databases, and files often return data in this structure.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ toString
Array.prototype.toString() - JavaScript - MDN Web Docs
If the join method is unavailable ...tring.call({ join: () => 1 })); // 1 ยท JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation....
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_tostring_array.asp
JavaScript Array toString() Method
The toString() method returns a string with array values separated by commas. The toString() method does not change the original array. Every JavaScript object has a toString() method.
๐ŸŒ
SamanthaMing
samanthaming.com โ€บ tidbits โ€บ 83-4-ways-to-convert-string-to-character-array
4 Ways to Convert String to Character Array in JavaScript | SamanthaMing.com
The key there is "copies all enumerable own properties". So what we're doing here Object.assign([], string) it copying ALL of our string properties over to our new array.
๐ŸŒ
Tabnine
tabnine.com โ€บ home โ€บ array to string in javascript
Array to String in JavaScript - Tabnine
July 25, 2024 - If we have an array that has a nested object, as defined in the following example, the resulting string value will contain [object Object]:
๐ŸŒ
Quora
quora.com โ€บ How-can-you-tell-whether-a-string-is-an-array-or-object-in-Javascript-NodeJS
How to tell whether a string is an array or object in Javascript/NodeJS - Quora
Answer: You cannot unless you knew it is a serialization. When you get q string, you always must parse it. If it was JSON representation, you vould check it by running: const parsed = JSON.parse(string); if (parsed instanceof Artay) { /* Array stuff */ } else if (typeof parsed === โ€œobjectโ€) ...
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_obj_string.asp
JavaScript String Reference
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS ... JS String JS Number JS Boolean JS BigInt JS Symbol JS undefined JS null JS undefined vs null JS Constructors ยท Array() BigInt() Boolean() Date() Error() Function() Map() Number() Object() Promise() RegExp() Set() String() Symbol() WeakMap() WeakSet() JS Operators JS Assignment
๐ŸŒ
Eloquent JavaScript
eloquentjavascript.net โ€บ 04_data.html
Data Structures: Objects and Arrays :: Eloquent JavaScript
Weโ€™d have to somehow extract the digits and convert them back to numbers to access them. Fortunately, JavaScript provides a data type specifically for storing sequences of values. It is called an array and is written as a list of values between square brackets, separated by commas.