0

I'm trying to parse some JSON data using jQuery and I'm having trouble trying 'target' certain entries because some of the JSON entries have illegal characters (such as :) and jQuery errors when these are fetched, with the message "Unexpected token : ".

Here is my jQuery script, where the first appendage gets the data without any errors ('j.profileInfo.profileName') and the second line is causing the issue ('j.totalsForAllResults.ga:visitors').

var myjson = '{
    "itemsPerPage": 50,
    "totalResults": 1,
    "profileInfo": {
        "profileId": "12345678"
    },
    "totalsForAllResults": {
        "ga:visitors": "100",
        "ga:newVisits": "30"
    }
}';

var j = $.parseJSON(myjson);

$("body").append("<h2>" + j.profileInfo.profileName + "</h2>");
$("body").append("<p>" + j.totalsForAllResults.ga:visitors + "</p>");

I'm fetching the json data from the Google API so I can't edit the JSON unfortunately. Is there another way I can target the data, perhaps something the long the lines of j.totalsForAllResults[0] so that I don't need to put the : in? Does anyone know of a solution to this problem?

mmmoustache
  • 2,273
  • 6
  • 41
  • 62

1 Answers1

1

Use bracket notation in that case instead of dot notation

j.totalsForAllResults['ga:visitors']

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531