I'm using an MVC app and my controller gets a string like this from mongodb:
str = "[{ title: 'My title', items: [{ name: 'item1', link: '#' }, { name: 'item2', link: '#' }] }]"
And I'm trying to use it in the view as a js Array, but I can't find any way to convert it.
Note that the array will have some sub arrays as items and some sub sub arrays, and so on.
Any help? Maybe I have to build the array inside my business layer instead of returning a string?
I'm using an MVC app and my controller gets a string like this from mongodb:
str = "[{ title: 'My title', items: [{ name: 'item1', link: '#' }, { name: 'item2', link: '#' }] }]"
And I'm trying to use it in the view as a js Array, but I can't find any way to convert it.
Note that the array will have some sub arrays as items and some sub sub arrays, and so on.
Any help? Maybe I have to build the array inside my business layer instead of returning a string?
Share Improve this question edited May 13, 2015 at 19:03 Kavesa asked May 13, 2015 at 18:59 KavesaKavesa 131 silver badge6 bronze badges 2- MVC is not an app. It's arcitectural pattern. Are you using ASP.NET MVC? – Vano Maisuradze Commented May 13, 2015 at 19:02
- can you change the format of that string? – Jeff Commented May 13, 2015 at 19:13
3 Answers
Reset to default 4Knowing nothing else about the structure of your app, the easy way to convert that string into an object is using eval()
.
var object = eval("[{ title: 'My title', items: [{ name: 'item1', link: '#' }, { name: 'item2', link: '#' }] }]");
That said, NEVER use eval()
on a string that you do not absolutely trust. It is very easily abused and exploited.
the solution is JSON: have a look at the docs: http://www.w3schools./js/js_json.asp
And here is what you'd need to do:
var obj = JSON.parse(str);
This will give you a Javascript-Object (JSON=JavaScriptObjectNotation) which you then can access like that:
var firstTitle = obj[0].title; // 'My title'
var itemsArrayOfFirstObject = obj[0].items; // an Array of items
var linkOfForstItemInFirstObject = obj[0].items[0].link; // '#'
EDIT:
I oversaw that in your example the string is not in valid JSON-format
Here's a function that will change the string to valid JSON, which is then returned as an object using JSON.parse()
:
function parse(str) {
var t= '',
special= '[]{} :,',
qt;
str= str.split('');
for(var i = 0 ; i < str.length ; i++) {
if((qt=str[i])==="'" || qt==='"') {
do {
t+= str[i++].replace("'",'"');
} while(i < str.length && str[i]!==qt);
t+= qt.replace("'",'"');
}
else if(special.indexOf(str[i])===-1) {
t+= '"';
do {
t+= str[i++];
} while(i < str.length && special.indexOf(str[i])==-1)
t+= '"';
i--;
}
else {
t+= str[i];
}
}
return JSON.parse(t);
} //parse
obj = parse("[{ title: 'My title', items: [{ name: 'item1', link: '#' }, { name: 'item2', link: '#' }] }]");
console.log(obj[0].items[1].name); //item2
I threw this together quickly, so I may be overlooking something. But it works with your example string.