0

Hi after a query in php and converting the results to JSON with json_encode i have this:

{"ga:visits":"59","ga:pageviews":"117","ga:timeOnSite":"4775.0","average_time_on_site_formatted":"0:01:20","pages_per_visit":"1.98"}

my problem is how to loop it and store the keys and values in different variables.

i`m not a javascript guy so please help and give good details.

best regards

Ron
  • 531
  • 8
  • 23

3 Answers3

3

You need to parse the JSON-string into a Javascript object first. Most browser nowadays have a native support for that in window.JSON.

var myObj = JSON.parse('{"ga:visits":"59","ga:pageviews":"117","ga:timeOnSite":"4775.0","average_time_on_site_formatted":"0:01:20","pages_per_visit":"1.98"}');

After that, you can just loop over the keys:

for(var key in myObj) {
    console.log(key, ' is: ', myObj[key]);
}

If you want to use that in "old'ish" browsers, like IE7 and below you need to use the json2.js from http://www.json.org to have the same functionality.

jAndy
  • 231,737
  • 57
  • 305
  • 359
1
var parsedObject = JSON.parse(str); //str - json string in your example
for(var key in parsedObject){
   // to access each key name - use "key"
   // to acces each value use parsedObject[key]
   document.writeln("key:" + key + "; value: " + parsedObject[key]);
}
Alexandr
  • 9,213
  • 12
  • 62
  • 102
0

I would suggest evaluating it with something like

var obj = eval(jsonString);

this will turn the entire string into an object with fields:

  • ga:visits
  • ga:pageviews
  • ga:timeOnSite
  • etc.

Then go you can access each variable by name, like obj.pages_per_visit

Ray
  • 4,829
  • 4
  • 28
  • 55
  • you would need to have "(" and ")" before and behind the JSON string to make that work. – jAndy Jan 24 '11 at 13:51