参考下面的代码,我从here获得,结果部分(第40行以后)将采用字符串格式。如何将其更改为JSON?到目前为止,我知道我需要包含JSON::Create
。在那之后,我不确定如何继续。
use Net::Google::Analytics;
use Net::Google::Analytics::OAuth2;
# Insert your numeric Analytics profile ID here. You can find it under
# profile settings. DO NOT use your account or property ID (UA-nnnnnn).
my $profile_id = "1234567";
# See GETTING STARTED for how to get a client id, client secret, and
# refresh token
my $client_id = "123456789012.apps.googleusercontent.com";
my $client_secret = "rAnDoMsEcReTrAnDoMsEcReT";
my $refresh_token = "RaNdOmSeCrEtRaNdOmSeCrEt";
my $analytics = Net::Google::Analytics->new;
# Authenticate
my $oauth = Net::Google::Analytics::OAuth2->new(
client_id => $client_id,
client_secret => $client_secret,
);
my $token = $oauth->refresh_access_token($refresh_token);
$analytics->token($token);
# Build request
my $req = $analytics->new_request(
ids => "ga:$profile_id",
dimensions => "ga:medium,ga:source",
metrics => "ga:bounces,ga:visits",
filters => "ga:medium==referral",
sort => "-ga:visits",
start_date => "2011-10-01",
end_date => "2011-10-31",
max_results => 5,
);
# Send request
my $res = $analytics->retrieve($req);
die("GA error: " . $res->error_message) if !$res->is_success;
# Print results
print
"Results: 1 - ", $res->num_rows,
" of ", $res->total_results, "\n\n";
for my $row (@{ $res->rows }) {
print
$row->get_source, ": ",
$row->get_visits, " visits, ",
$row->get_bounces, " bounces\n";
}
print
"\nTotal: ",
$res->totals("visits"), " visits, ",
$res->totals("bounces"), " bounces\n";
修改
我已经从# Print results
开始编辑了我的代码:
# Print results
print
"Results: 1 - ", $res -> num_rows,
" of ", $res -> total_results, "\n\n";
for my $row(@{
$res -> rows
}) {
%hash = ("source:" => $row -> get_source, "visits:" => $row -> get_visits, "bounces:" => $row -> get_bounces, "sessions:" => $row -> get_sessions, "users:" => $row -> get_users);
print create_json (\%hash);
print ("\n");
}
我的输出最终是JSON格式:
{"source:":"pinterest.com","visits:":"17497","sessions:":"17497","bounces:":"13625","users:":"17882"}
{"visits:":"6223","sessions:":"6223","source:":"m.facebook.com","bounces:":"4693","users:":"6298"}
{"visits:":"2612","sessions:":"2612","source:":"pinterest.com","bounces:":"1945","users:":"1766"}
{"users:":"933","source:":"m.facebook.com","sessions:":"1671","visits:":"1671","bounces:":"1334"}
{"users:":"422","bounces:":"728","visits:":"1125","sessions:":"1125","source:":"disq.us"}