Reputation: 1389
I have this wrong Json string:
({loc: '(49.150892549035454, 9.22825813293457)' , shopName: 'Otest', nameID: '1', apID: 'Loa', gender: 'male'}); ({loc: '(12.150892549035454, 12.22825813293457)' , shopName: 'OtestRe', nameID: '1', apID: 'Loaa', gender: 'female'});
So now I tried to correct the string with:
var res = this.markerlist.replace(/\)|\(/g, '');
var res2 = res.replace(/;/g, ',');
var jsonList = JSON.stringify('[' + res2 + ']';
[{loc: '(49.150892549035454, 9.22825813293457)' , shopName: 'Otest', nameID: '1', apID: 'Loa', gender: 'male'}, ({loc: '(12.150892549035454, 12.22825813293457)' , shopName: 'OtestRe', nameID: '1', apID: 'Loaa', gender: 'female'}]
Then I try to parse it:
var jsonRs = JSON.parse(jsonList);
for (var rowData in jsonRs) // for acts as a foreach
{
console.log(jsonRs[rowData]);
}
And I get every character as output like:
4
9
.
1
And so on.
Upvotes: 2
Views: 795
Reputation: 51841
You can parse your input like this:
var input = "({loc: '(49.150892549035454, 9.22825813293457)' , shopName: 'Otest', nameID: '1', apID: 'Loa', gender: 'male'}); ({loc: '(12.150892549035454, 12.22825813293457)' , shopName: 'OtestRe', nameID: '1', apID: 'Loaa', gender: 'female'});";
var result = input
.split(";") // spliting ';' for each object
.slice(0, -1) // removing last portion after ';'
.map(function(item) {
var cleaned = item
.trim() // removing white spaces from the ends
.slice(1, -1) // getting rid of ()
.replace(/'/g, '"') // replacing ' to "
.replace(/(\w+):/g, '"$1":'); // surrounding word before ':' with double quotes
return JSON.parse(cleaned);
});
console.log(result);
Upvotes: 1
Reputation: 577
Here another version with loc
property as Array so you could use lattitude
ang longitude
var markerlist = "({loc: '(49.150892549035454, 9.22825813293457)' , shopName: 'Otest', nameID: '1', apID: 'Loa', gender: 'male'}); ({loc: '(12.150892549035454, 12.22825813293457)' , shopName: 'OtestRe', nameID: '1', apID: 'Loaa', gender: 'female'});";
var arStr = markerlist.split(";");
var jsons = [];
for(var i=0;i < arStr.length;i++){
var o = eval(arStr[i]);
if(o){
o.loc = o.loc
.replace(/\(|\)/g, "")
.split(',');
jsons.push(o);
}
}
console.log(jsons);
Upvotes: 0
Reputation: 13151
Although as everyone suggested, knowing the format is important to solve your problem. So your approach to replace & parse is wrong & error prone.
Your Json string is actually javascript... So even an eval could work.
EDIT : As pointed out by Biwise Creative, it would need bit of treatment :
this.markerlist.split(";").slice(0,-1).map(function(t) {return eval(t);})
Upvotes: 4