JSON response from Google Analytics api - javascript

I am using the google-api-ruby-client to get a response from the Google Analytics api, which is successful, the one thing I am a little confused with though is the response object. I would like to know how to drill down into specific keys and their values or even parse the response to make it more understandable.
Below is what I believe is the relevant part of the JSON response
"{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"query\":{\"start-date\":\"2014-01-01\",\"end-date\":\"2014-07-22\",\"ids\":\"ga:88893966\",\"dimensions\":\"ga:pagePath\",\"metrics\":[\"ga:pageviews\"],\"filters\":\"ga:pagePath==/\",\"start-index\":1,\"max-results\":1000},\"itemsPerPage\":1000,\"totalResults\":1,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"profileInfo\":{\"profileId\":\"88893966\",\"accountId\":\"53082810\",\"webPropertyId\":\"UA-53082810-1\",\"internalWebPropertyId\":\"85713348\",\"profileName\":\"All Web Site Data\",\"tableId\":\"ga:88893966\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:pagePath\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:pageviews\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:pageviews\":\"8\"},\"rows\":[[\"/\",\"8\"]]}"
which is obtained from
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
puts ap(result)
Also when I do:
puts ap(result.data.rows.inspect)
#returns
"[[\"/\", \"8\"]]"
and when i try
response = JSON.parse(result.data.totalsForAllResults)
puts ap(response)
# returns error
TypeError: no implicit conversion of #<Class:0x00000001950550> into String
I am wondering how I can format the response without the backslashes and how I would say get the total page views?

Your syntax is off.
If result is simply a string that is a json object, which it looks like above, what you want is:
response = JSON.parse(result)
ap response["totalsForAllResults"]["ga:pageviews"]
Looking at the google-api-ruby-client the result.data returns an object if parseable from api schema, a hash if you pass the media type "application/json", or a string otherwise. So you need to determine if you are accessing the response data as an object or a Hash. My example above parses the raw string into a ruby hash.
tl;dr; there are multiple ways to attain the data you want.

Yes, your syntax is off. It should look something like this.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:_____&dimensions=ga:date&metrics=ga:impressions,ga:adClicks,ga:adCost&start-date=2015-10-13&end-date=today
BaseUrl, id, metrics, start-date and end-date are required. And don't forget to insert the access_token as well.

Related

How I can fetch textarea data to node js

I cannot send data of <textarea> to node js, Node js don't see the my sent data.
For Fetch data to Node Js
continueBtn.addEventListener("click", async () => {
console.log(myMsg.value)
console.log(typeof(myMsg.value))
const req = await fetch("/sendmsg", {method: "POST",body: myMsg.value}) ;
console.log("Fetched")
})
For get data in Node js
const {userMessage} = Object.keys(req.body)
You are passing a string to body. Since you aren't overriding it, it will be given a text/plain content-type.
On the server you expect req.body to contain an object.
You haven't shown us what, if any, body parsing middlewares you have configured in your server side code, but none of the common ones will convert something that is text/plain into an object.
You should:
Make sure that you have a body parsing middleware configured
Encode the data you are passing to body (e.g. with URLSearchParams) so it has name=value pairs instead of being a plain string.
If you end up passing a string (e.g. if you pass a string of JSON instead of a URLSearchParams object) then you'll also need to set a Content-Type request header that matches your data format.
"const {userMessage} = Object.keys(req.body)"
I don't see why you'd be expecting to have a userMessage key in your body object with the code you pasted. It's possible the data is being passed properly, but you are trying to access the wrong key. I would try logging in your server code to debug the response format as a first step:
console.log(JSON.stringify(req.body))
Let me know if that gets you enough help to move forward, and I can circle back here if not.

Data coming from backend is stored in object but not accessible in object properties

Data coming from backend is stored in object but when i tries to print in using object properties its showing undefined. Here is my output:
enter image description here
my code:
this.documentService.getDocumentbyId(this.id).subscribe(
data => {
this.upmDoc=data;
console.log("UPM Data Fetched:",this.upmDoc);
console.log("Name:",this.upmDoc.name);
console.log("Symbolic Name:",this.upmDoc.symbolicName);
console.log("Object Store:",this.upmDoc.objectStore);
console.log("Active:",this.upmDoc.active);
},
error => console.log(error)
);
Its better to provide the response JSON instead of image to make sure where the problem is.
It looks like your service return HTTP Response not the body of the response. try to access the body of the data instead. replace the third line with:
this.upmDoc = data.body;
or
this.upmDoc = data["Document Details"];
based on your returned JSON.

How can I make my API website json value into a new variable?

I need to convert a username to an ID. Here’s my API link: https://api.mojang.com/users/profiles/minecraft/username (username is replaced by the variable “name”.) So from that link I need to get the ID value and save it to a variable called “uuid”.
Thanks,
Nathan
Here’s a valid url for viewing: https://api.mojang.com/users/profiles/minecraft/_Pine
So, when you fetch the JSON object from that API, you need to parse it using JSON.parse(). So, for example:
let myUserInfo = JSON.parse(fetchResult);
let uuid = myUserInfo.id;
So, given that you currently don't know about fetch(), I'd suggest learning that. fetch is a javascript Promise object, a new part of the language that greatly simplifies grabbing data from open API's (for example). Here's a simple fetch statement for that URL:
let myUserUrl = "https://api.mojang.com/users/profiles/minecraft/_Pine";
fetch(myUserUrl)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson.id);
});
Note that this won't run on stackoverflow, as it crashes into a cross-origin error. Depending on where and how you are serving this, let us know if it works for you, or if you get stuck.

Javascript: send object with object inside trought post method

I'm pretty new to javascript and i'm trying to send an object with an other object inside trought post method:
$.post('/posttest', {tableName : 'WSTest', data : {name : "Rachid", age : 42, ville : "Tokyo"}}).done(function(data) {
console.log("data posted : ", data);
});
I can retrieve tableName with req.body.tableName but req.body.data give me undefined. When i console.log(req.body) i got:
{ tableName: 'WSTest',
'data[name]': 'Rachid',
'data[age]': '42',
'data[ville]': 'Tokyo' }
As far as i understand it, javascript takes data as a dico ? How can i make data as an object ?
Standard form encoded data is a flat data structure. It is just key/value pairs.
A non-standard extension to the syntax was introduced by PHP which allows you to describe nested data, but your parser doesn't appear to recognise it.
To access the data you will need to mention the square brackets.
req.body["data[name]"]
// etc
Alternatively, find a parser which does recognise the square brackets as having special meaning.
Assuming you are using the (fairly common) "URL-encoded form body parser" feature of the body-parser module, see the docs:
extended
The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.
So:
app.use(bodyParser.urlencoded({ extended: true }));
… will probably do the trick.

How can I send foreign characters with YUI io (XMLHttpRequest)

I'm using YUI io to post data to my server. I have some problems sending foreign characters like æ ø å.
First case: a form is posted to the server
Y.io(url, {
method: 'POST',
form: {
id: 'myform',
useDisabled: true
}
});
This will post the content of the form to the server. If I have a field named "test1" containing "æøå", then on the server I'll see REQUEST_CONTENT="test1=%C3%A6%C3%B8%C3%A5". This can be easily decode with a urldecode function, NO PROBLEM, but...
Second case: data is posted this way:
Y.io(uri, {
data : '{"test1":"æøå"}'),
method : "POST"
});
Now I see this on the server REQUEST_CONTENT="{"test1":"├ª├©├Ñ"}". How can I decode that? And why is it send like that?
I know I can use encodeURIComponent() to encode the string before sending it. But the io request is actually part of a Model Sync operation, so I'm not calling io directly. I'm doing something like this:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {....});
var user = new Y.User();
user.set('test1', 'æøå');
user.save();
So it doesn't make sense to encode/decode everytime I set/read the attribute.
Also I have tried to set charset=utf-8 in the request header, but that didn't change anything.
EDIT
I have done some more debugging in chrome and the request is created with this line of code:
transaction.c.send(data);
transaction.c is the xmlhttprequest and (using chrome debugger) I can see the data is "{"test1":"æøå"}"
When the above line of code is executed, a pending network entry is shown (under the network tab in chrome debugger). Request payload displays {"test1":"├ª├©├Ñ"}
Headers are:
Accept:application/json
Content-Type:application/json; charset=UTF-8
ModelSync.REST has a serialize method that decides how the data in the model is turned into a string before passing it to Y.io. By default it uses JSON.stringify() which returns what you're seeing. You can decode it in the server using JSON. By your mention of urldecode I guess you're using PHP in the server. In that case you can use json_decode which will give you an associative array. If I'm not mistaken (I haven't used PHP in a while), it should go something like this:
$data = json_decode($HTTP_RAW_POST_DATA, true);
/*
array(1) {
["test1"] => "æøå"
}
*/
Another option would be for you to override the serialize method in your User model. serialize is a method used by ModelSync.REST to turn the data into a string before sending it through IO. You can replace it with a method that turns the data in the model into a regular query string using the querystring module:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {
serialize: function () {
return Y.QueryString.stringify(this.toJSON());
}
});
Finally, ModelSync.REST assumes you'll be using JSON so you need to delete the default header so that IO uses plain text. You should add this at some point in your code:
delete Y.ModelSync.REST.HTTP_HEADERS['Content-Type'];

Categories