I have this string which I get from code behind:
{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}
I need to convert it to an array of objects like this:
var Categories =
[
{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"},
{Name:"Dress", CatGroupName:"Clothes", Gender:"female"},
{Name:"Belt", CatGroupName:"Leather", Gender:"child"}
];
Because I need to perform some functions on it. (like $.grep and so on)
How can I convert it? Thanx in advance.
asked Sep 18, 2015 at 15:52
Payam Sh
6015 gold badges10 silver badges23 bronze badges
1 Answer 1
The best solution is to make the backend return proper JSON and you do not have to do anything special to process it on the client. To make it valid JSON, you need to wrap the keys with double quotes and wrap the entire string with brackets to make it an array.
BUT if you can not touch the back end, you can use new Function to convert it.
var str = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';
var obj = (new Function("return [" + str + "];")());
console.log(obj);
answered Sep 18, 2015 at 16:06
epascarello
208k20 gold badges206 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Stumblor
Interesting solution! Beats using JSON.parse :-)
Payam Sh
Thanx dear epascarello. Didn't know there's a solution like this!
epascarello
@Stumblor That is what a lot of the JSON.parse polyfills do under the hood and why the pollyfills normally allow invalid JSON. :)
lang-js
JSON.parse. Also this is not an associative array, it's an array of objects.JSON.parseinstead.