How to parse json response from Bigquery results? - javascript

I tried sample javascript code to call Google bigQuery API ( https://developers.google.com/bigquery/docs/authorization#client-side-javascript )
Js:
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT TOP(repository_language, 5) as language, COUNT(*) as count FROM [publicdata:samples.github_timeline] WHERE repository_language != "";'
});
request.execute(function(response) {
console.log(response);
var results = response.result.rows ;
$('#result_box').html(JSON.stringify(results, null));
});
}
Above big query returns :
[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]
Please help me how to parse the values from above results in JSON Format ?
{"JavaScript": "949899", "Ruby": "640659", "Java": "568202", "Python": "484852", "PHP": "453830" }

Eval is a security risk.
var text = '[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';
myData = JSON.parse(text);
alert(myData[4].f[0].v);​

http://jsfiddle.net/jv7vm/
var a='[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';
var evala=eval('('+a+')');
for(i=0;i<evala.length;i++)
{
document.write(evala[i].f[0].v+' '+evala[i].f[1].v+'<br>');
}

Got answer from below javascript
var total = response.result.totalRows;
var data = [];
for(i=0; i < total; i++){
data[i]= [ response.rows[i].f[0]["v"], response.rows[i].f[1]["v"] ];
}
console.log(data);

Related

Parse Cloud code query.withinKilometers

(Edit 1)
I'm trying to work with the cloud code and GeoPoint. With the function "query.withinKilometers" I have a pointer to the Location Class but when I try to call the function I get the error "invalid key name". What is the right way to do this? I could not find anything in the documentation, here is a file of the cloud function.
Error: "code":105,"message":"Invalid key name: [object Object]"
here de documentation: http://parseplatform.org/Parse-SDK-JS/api/v1.11.1/Parse.html
Parse.Cloud.define("getCloseFindings", function(request, response){
var query = new Parse.Query("findings");
var locQuery = query.include("location");
var LocQuery = locQuery.get("geoLocation");
var Loc_Lat = request.params.Latitude;
var Loc_Long = request.params.Longitude;
var UserLocation = new Parse.GeoPoint(Loc_Lat,Loc_Long);
var RadiusLocation = request.params.Radius;
query.equalTo("isDeleted", false);
query.withinKilometers(locQuery, UserLocation, 100);
query.find({
success: function(results){
if(results === undefined){
var response_jsonArr = {
code : 404,
message : "Not Found"
};
response.success(response_jsonArr);
}else{
var jsonArr = [];
for ( var i = 0; i < results.length; ++i ) {
var finding_location = results[i].get("location");
jsonArr.push({
name: results
});
}
response.success(jsonArr);
}
}, error: function(error){
response.error(error);
}
});
You are passing an object to query.withinKilometers as the first parameter when you should be passing a String. Try using the key from your query.include call instead, like this:
query.withinKilometers("location", userLocation, 100);

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Extracting Data from non-JSON API url

I would to set expectations first. I know basic HTML, and understand CSS, vbScript and JavaScript but not an expert, not even intermediate.
I want to extract data from an API url that looks like this...
and the browser returns these data...
Domain;Rank;Organic Keywords;Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic;Adwords Cost
somedomain.com;31970;26015;35679;252734;0;0;0
How can I get these data into a JSON file so I can create a JavaScript for it.
Thanks!
You can split the String, then assign the parts to an object manually:
var response = "Domain;Rank;Organic Keywords;Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic;Adwords Cost;somedomain.com;31970;26015;35679;252734;0;0;0";
var fields = ["Dn", "Rk", "Or", "Ot", "Oc", "Ad", "At", "Ac", null, "v1", "v2", "v3", "v4"];
var data = response.split(";");
var parsedData = {};
fields.forEach(function(fld, i) {
if (fld) parsedData[fld] = data[i];
});
console.log(parsedData);
http://codepen.io/anon/pen/yavrYj?editors=1111
split by the semicolon, break them up into two arrays (key, value) then make the json object
var data = "Domain; Rank; Organic Keywords; Organic Traffic;Organic Cost;Adwords Keywords;Adwords Traffic; Adwords Cost; somedomain.com;31970;26015;35679;252734;0;0;0"
var values = data.split(";")
var half = values.length / 2
var keys = values.splice(0,half);
var jsonData = {};
for (i = 0; i < keys.length; i++) {
jsonData[keys[i]] = values[i]
}
the result is
Object {
Adwords Cost: "0",
Organic Keywords: "26015",
Organic Traffic: "35679",
Rank: "31970",
Adwords Keywords: "0",
Adwords Traffic: "0",
Domain: " somedomain.com",
Organic Cost: "252734"
}
you had asked in your comment how do you get your data from the api?
If you are using jquery ajax I guess it would be something like
$(function() {
$.ajax("http://api.domain.com/?type=domain_rank&key=somekey&export_columns=Dn,Rk,Or,Ot,Oc,Ad,At,Ac&domain=somedomain..com&database=us",
{
type: 'get',
cache: false,
dataType: 'text',
contentType: "application/json",
success: function (data) {
var values = data.split(";")
var half = values.length / 2
var keys = values.splice(0,half);
var jsonData = {};
for (i = 0; i < keys.length; i++) {
jsonData[keys[i]] = values[i]
}
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
});
however if you are attempting to call this api from javascript on a different domain you may run into CORS problems.

Getting data from JSON Structure

My coldfusion component is returning a JSON format data. I am trying to access the values of that data in my front-end using Javascript. Can someone help me understand how to access the data values such as the "id", "firs_name" and "last_name"?
I am storing the the follow data in the variable called tempData. Below is the JSON structure I am getting:
{ "COLUMNS" : [ "id",
"FIRST_NAME",
"LAST_NAME"
],
"DATA" : [ [ "xxxx",
"Jes",
"Abr"
],
[ "xxx2",
"JESSIE",
"YU"
]
]
}
Below is my ajax call:
$.ajax({
type: "get",
url: "GROUPSLIST.cfc",
data: {
method: "getNames",
queryString: selectQuery
},
success: function(a) {
alert(a);
},
error: function(a) {
alert(a.responseText);
}
});
I am assuming your response is not parsed already. You can use something like following.
var tempData = '{"COLUMNS":["id","FIRST_NAME","LAST_NAME"],"DATA":[["xxxx","Jes","Abr"],["xxx2","JESSIE","YU"]]}';
//parse response if not already parsed
var respObj = JSON.parse(tempData);
var columns = respObj['COLUMNS'];
//create a column map to index like following
var colMap = {};
for(i = 0; i < columns.length; i++){
colMap[columns[i]] = i;
}
console.log(colMap)
var data = respObj['DATA'];
var text = ''
//use data[i][colMap['id']] to access data inside loop.
for(i = 0; i < data.length; i++){
text += data[i][colMap['id']] + ':' +data[i][colMap['FIRST_NAME']] + ' ' + data[i][colMap['LAST_NAME']] + '<br>';
}
document.getElementById('text').innerHTML = text;
<div id="text"></div>
This might be also help full while using DB query and access by column(ex:employee_id,employee_name)
Step-1
// return in serializeJSON format with true
<cffunction name="employeelistJson" returntype="any" returnformat="JSON">
<cfquery name="employeelist" datasource="yourdatasource">
select * from employee
</cfquery>
<cfset setJson = #serializeJSON(employeelist,true)#>
<cfreturn setJson />
</cffunction>
Step-2 access json data by name
success: function(response) {
//must be in caps
alert(response.DATA['EMPLOYEEID']);
alert(response.DATA['EMPLOYEENAME']);
},

retrieve value in unnamed json array url

I'm struggling to retrieve some value on a json in this url:
http://go-gadget.googlecode.com/svn/trunk/test.json
the url data looks like this:
[
{
"key":{
"parentKey":{
"kind":"user",
"id":0,
"name":"test 1"
},
"kind":"smsgateway",
"id":5707702298738688
},
"propertyMap":{
"content":"test1 content",
"date":"Dec 12, 2013 2:58:57 PM",
"user":"test1"
}
}]
By ignoring the "key", I want to access the value of "propertyMap" object (content,date and user) using javascript code.
I have tried this code but it couldn't get the result:
var url = "http://go-gadget.googlecode.com/svn/trunk/test.json";
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
var content = json[i].propertyMap.content;
console.log('content : ', content);
var user = json[i].propertyMap.user;
console.log('user: ', user);
var date = json[i].propertyMap.date;
console.log('date : ', date);
}
});
(unsuccessful code here http://jsfiddle.net/KkWdN/)
considering this json can't be change, is there any mistake I've made from the code above or there's any other technique to get the result?
I just learn to use javascript and json for 1 month so response with an example is really appreciated.
--edited: I change [].length to json.length, now I'm looking for the answer to access the url
That would be something like :
$.getJSON("http://go-gadget.googlecode.com/svn/trunk/test.json", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.content;
var user = map.user;
var date = map.date;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
But the request fails, as no 'Access-Control-Allow-Origin' header is present on the requested resource, so you're being stopped by the same origin policy
What do you think [].length; would evaluate to .
It is 0 , so it would never go inside the for loop.
Other than that you code looks ok.
Replace your for loop as below
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
Also you seem to be accessing a API as part of the different domain.
So you need to use CORS or JSONP to get this working if you want to retrieve data from a different domain.
Change:
for (var i = 0; i < [].length; i = i + 1) {
to
for (var i = 0; i < json.length; i = i + 1) {
DEMO here.
How about using something like the following
In your case, say the object is myObj, I would get the value like this
var content = fetchValue(myObj, [0, "propertyMap", "content"], "");
var date = fetchValue(myObj, [0, "propertyMap", "date"], new Date());
var user = fetchValue(myObj, [0, "propertyMap", "user"], "");
Just to make sure that we send a default value in case we do not get the desired ojbect. The beauty of this approach is that now you do not have to worry about array or objects nested in the structure. The fetchValue function could be something like below.
function fetchValue(object, propertyChain, defaultValue){
var returnValue;
try{
returnValue = object;
forEach(propertyChain, function(element){
returnValue = returnValue[element];
});
}catch(err){
return defaultValue;
}
if(returnValue == undefined) {
returnValue = defaultValue;
}
return returnValue;
}
Adding the forEach function
function forEach(array, action){
for(var x in array)
action(array[x]);
}

Categories

Resources