June
June

Reputation: 823

html 5 attribute as array of object being treated as string

I am trying to create a code snippet that fetches google map objects like location, marker text from database and add it to html data-attributes so I can use them in javascript easily

I am unable to make js understand the json as json , its rather being treated as string

	jQuery('.map_canvazz').each(function(i,elem) {
		latPos			=	jQuery(this).attr("data-lat");
		longPos			=	jQuery(this).attr("data-long");
		infoDisplay		=	jQuery(this).attr("data-info");
		var objAddresses=	jQuery(this).attr("data-params");
        
      if(typeof objAddresses != 'undefined'){
			console.log(typeof(objAddresses));
			console.log(objAddresses);
			//array of object is treated as string
            // unable to convert array of objects as json
            // todo :- loop through the object of array
		}
      
      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='map_canvazz' id='maper1'   data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div>					</div>

Upvotes: 1

Views: 211

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Use .data() jq method. It will parse it to array:

jQuery('.map_canvazz').each(function(i, elem) {
  var objAddresses = jQuery(this).data("params");
  for (var i = 0; i < objAddresses.length; i++) {
    var obj = objAddresses[i];
    console.log(obj.lat, obj.long, obj.mapTxt);
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='map_canvazz' id='maper1' data-params='[{"lat":"-36.758435","long":"144.273174","mapTxt":"<div class=\"mapArea\"><div class=\"lineOneMap\">Beyond Medical Education Victorian Office<\/div><div class=\"lineTwoMap\">37 Rowan Street<br>Bendigo VIC 3550, Australia<br>+61 35441 9300<\/div><\/div>"},{"lat":"1111","long":"222","mapTxt":"test"}]'></div>
</div>

Upvotes: 1

Quentin
Quentin

Reputation: 943615

Attribute values can only be strings. If you want to convert a string of JSON into a JavaScript object then you should run it through JSON.parse().

Upvotes: 2

Related Questions