I have a string [{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]
I want output as [{8.55701,76.880934},..etc] only numbers.
This is a JSON string -
<script type="text/javascript">
var myVar = ' <%= request.getAttribute("Map") %>'; /* retrieve json from request attribute */
var result = myVar.split(',',2);
var latitude = parseFloat(result[0].replace('"Latitude":',''));
var longitude = parseFloat(result[1].split(':'));
alert(latitude);
</script>
I have tried but not getting it.
4 Answers 4
Use simple Regular expression to remove the strings:
.replace(/\"\w+\":/g, '');
'[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]'.replace(/\"\w+\":/g, '');
And if you want to get the values you can use JSON.parse:
var coords = JSON.parse('[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]');
// And loop
coords.forEach(function(coord) {
console.log('latitude', coord.Latitude);
console.log('longitude', coord.Longitude);
});
1 Comment
try this, this function will return a string as you expected out put.
function pareseJSONStr(str){
var json = JSON.parse(str);
var rslt = [];
json.forEach(function(obj){
rslt.push("{" + obj.Latitude + ", " + obj.Longitude + "}");
});
return "[" + rslt.join(",") + "]"
}
call this function as
var mystr = '[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]';
pareseStr(mystr);
returns a string
"[{8.55701, 76.880934},{8.55701, 76.880935},{8.55701, 76.880935}]"
Comments
If you really want your strange data format just use it:
var convertStrange = function( string ) {
return '[' + JSON.parse( string ).map( function( item ) {
return '{' + [ item.Latitude, item.Longitude ].join( ',' ) + '}';
} ).join( ',' ) + ']';
};
So,
convertStrange('[{"Latitude":8.55701,"Longitude":76.880934},{"Latitude":8.55701,"Longitude":76.880935},{"Latitude":8.55701,"Longitude":76.880935}]')
will return string
[{8.55701,76.880934},{8.55701,76.880935},{8.55701,76.880935}]
5 Comments
{8.55701,76.880934}
is wrong object construction. Objects must be name:value pairs so it can only be
{name1:8.55701, name2:76.880934}
or you can use an array like
[[8.55701, 76.880934], ... ]
if you want it as a string use this;
var string = '[{"Latitude":8.55701,"Longitude":76.880934}, {"Latitude":8.55701,"Longitude":76.880935}, {"Latitude":8.55701,"Longitude":76.880935}]';
var newString = string.replace(/\"Latitude\":|\"Longitude\":/g, "");
split()method?JSON.parseetc..? What have you tried? SO is not a free mechanical turd.eval()orJSON.parse()?