I am trying to query data form Google Spreadsheet available to be read by anyone with the Read Only link.
I implemented this Quickstart solution but here is what I need:
Access data just with URL, no authentication needed
Query item in column A and get value in column B
No need for updating any data
I tried constructing queries like:
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=C298732300456446&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
But all I get is:
/*O_o*/
google.visualization.Query.setResponse(
{
"version": "0.6",
"reqId": "0",
"status": "error",
"errors": [
{
"reason": "invalid_query",
"message": "INVALID_QUERY",
"detailed_message": "Invalid query: NO_COLUMN: C298732300456446"
}
]
}
This comes when the data is actually present in the sheet in column A with value C298732300456446.
What can I do for getting the data, without any authentication from my spreadsheet?
I am not sure if this can be done. If fine, I can suggest an alternative solution. You can try writing a Google App script like:
function doGet(e) { return getInfo(e); }
function doPost(e) { return getInfo(e); }
function getInfo(request) {
var someValueFromUrl = request.parameter.value;
var requiredValue = "";
var sheet = SpreadsheetApp.openById("spreadsheet_id");
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log("Reading row num: " + i);
if(data[i][0] == someValueFromUrl) {
requiredValue = data[i][1];
break;
}
}
Logger.log(requiredValue);
return ContentService.createTextOutput(JSON.stringify(requiredValue));
}
This way, you can publish this script as web app and call it using an URL which will be obtained when you publish this script.
Call the script like:
https://script.google.com/macros/s/obtained_url/exec?value=1234
If key is found, you will get the String response as:
"value"
I hope this helps.
C298732300456446 needs to be put within single quotes.
So you need to enclose C298732300456446 as %27C298732300456446%27
Your'e modified query would be
http://spreadsheets.google.com/tq?tq=SELECT%20*%20WHERE%20A=%27C298732300456446%27&key=2aEqgR1CDJF5Luib-uTL0yKLuDjcTm0pOIZeCf9Sr0wAL0yK
I'm unable to test this though - looks like you've removed/removed access from this spreadsheet.
Related
I am converting an iOS app to Android. The app is using Parse as backend.
I have stuck at this particular line (nested pointer, if I am correct) :
userQuery.includeKey("favoriteHouses.landlord")
Now I do not know how to convert this to Android :
parseQuery.include("favoriteHouses.landlord");
The above conversion does not yield any results.
Actually, I am able to get the array of pointers. But I also want to retrieve the rows of user table which exists in a field called landlord in another table.
Here is the case :I have two tables: One is "House" and other is "User" . A user can mark houses favorite. So the favorite marked houses are stored as array of pointers in the user table.These pointers point to the houses in the house table. In the house table, there is pointer type field called landlord which contains the object id of user and is of pointer type. So, while fetching those fav houses I also want the user's by using that landlord pointer which points back to the user table.
And the whole code that I am translating to android is :
// A query which will return the internal array of the object received by the objectQuery
class PFArrayQuery: PFQuery {
var objectQuery: PFQuery
var returnsKey: String
init(className: String, objectQuery: PFQuery, returnsKey: String) {
self.objectQuery = objectQuery
self.returnsKey = returnsKey
super.init(className: className)
}
override func findObjectsInBackgroundWithBlock(block: PFQueryArrayResultBlock?) {
objectQuery.getFirstObjectInBackgroundWithBlock { (result: PFObject?, error: NSError?) in
if let error = error {
block?(nil, error)
} else if let array = result?[self.returnsKey] as? [PFObject] {
block?(array, nil)
} else {
block?([], nil)
}
}
}
}
Now the above class is used like this :
override func queryForTable() -> PFQuery {
let emptyQuery = PFQuery()
guard let user = User.currentUser(),
userQuery = User.query() else {
return emptyQuery
}
let query = PFArrayQuery(className: "House", objectQuery: userQuery,
returnsKey: "favoriteHouses")
userQuery.includeKey("favoriteHouses")
// this is the line which I am unable to translate.
**userQuery.includeKey("favoriteHouses.landlord")**
userQuery.whereKey("objectId", equalTo: user.objectId ?? "")
return query
}
And now my translated code is :
ParseQuery parseQuery = ParseQuery.getQuery("House");
parseQuery.include("favoriteHouses");
parseQuery.include("favoriteHouses.landlord");
parseQuery.whereEqualTo("objectId",ParseUser.getCurrentUser().getObjectId());
I have also explained my situation here on this page :
Please correct me.
Thanks
I have created a simple REST API using Flask for an Android application. I'm having trouble implementing the GET method. It is supposed to return all the records in the form of a JSONArray. The response would look something like his
{
"tasks": [{
"task" : "Do it",
"timestamp": 1433510946152
},{..}
],
"success": 1
}
My Task model looks like this
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
task= db.Column(db.Text, nullable=False)
timestamp = db.Column(db.Integer, nullable=False)
#staticmethod
def newest():
return Task.query.order_by(desc(Task.timestamp))
def to_json(self):
return dict(id=self.id,
task= self.task,
timestamp = self.timestamp)
The to_json() method converts the result into JSON. I just don't know how to use it appropriately. How would I put all the records inside of an JSONArray? Here is my method that gets all the tasks. I'm using Flask paginate too, so tasks is a pagination object.
def get_tasks():
page = request.args.get('page')
if page is not None:
try:
page = int(request.args.get('page'))
except:
return jsonify({'result': 'Invalid parameter'})
else:
page = 1
tasks= models.Task.newest().paginate(page, 7, True)
#How do I return the tasks in an appropriate format?
Any help would be appreciated. Thanks.
Simply loop over your tasks, convert them into json using your to_json and store them inside of an array. For example:
def get_tasks():
page = request.args.get('page')
if page is not None:
try:
page = int(request.args.get('page'))
except:
return jsonify({'result': 'Invalid parameter'})
else:
page = 1
tasks= models.Task.newest().paginate(page, 7, True)
# This list will hold all your tasks in JSON format
jsontasks = []
# Since tasks is a pagination object, you should use tasks.items
for task in tasks.items:
jsontasks.append(task.to_json())
#How do I return the tasks in an appropriate format? Like this..
return jsonify({'tasks': jsontasks, 'success': 1})
I'm using Azure Mobile Services with an android application which I am trying to get working with a SQL database in Azure. Im using a server-side JavaScript function within Mobile Services to handle the insertion and update of data. Insertion of new data operates correctly, however I cannot update any rows with the function.
The error I received is: 409 - error: Could not insert the item because an item with that id already exists.
It seems as though it is trying to insert instead of update, but I can't figure out the solution. Help is much appreciated!
Here's my server-side script from Azure:
function insert(item, user, request) {
var table = tables.getTable('Reviews');
table.where({
text: item.id
}).read({
success: upsertItem
});
function upsertItem(existingItems) {
if (existingItems.length == 0) {
item.numReviews = 1;
item.rating = item.reviews;
request.execute();
} else {
item.id = existingItems[0].id;
item.numReviews = existingItems[0].numReviews + 1;
var average = existingItems[0].reviews / item.numReviews;
item.reviews = existingItems[0].reviews + item.reviews;
item.rating = average;
table.update(item, {
success: function(updatedItem) {
request.respond(200, updatedItem)
}
});
}
}
}
For your initial query, you want to query by the id field:
table.where({
id: item.id
}).read({
success: upsertItem
});
I tried to use the fql query to get json response,I used this code for doing this
String postid=jsonObject.getString("id");
String query = "SELECT likes.user_likes FROM stream WHERE post_id = \'" + postid + "'";
Bundle params = new Bundle();
params.putString("method", "fql.query");
params.putString("query", query);
String fqlResponse = Utility.mFacebook.request(params);
System.out.println(fqlResponse);
But I am getting null pointer exception at Utility.mFacebook.request(params);
I am using the default class in Github
I personally find the Facebook Graph API a little inadequate at times. For example, in your current requirement, if you need to use just the Graph API, you will need to first, get a list of all Users who have liked a particular post. After you have a list, you will then have to check if the User ID matches that of the logged in User and then, based on the result, run a function or something.
Instead, FQL offers a simpler function. In my app, for the exact same function, I exclusively make use of FQL.
You can fire a simple query. For example:
SELECT likes.user_likes FROM stream WHERE post_id ='XXXXXXXXXXXXX_XXXXXXXXX'
Replace the X's with the Post's ID. Make sure you surround the Post ID with 'YOUR_POST_ID'
Try it like this in the Graph API Explorer: fql?q=SELECT likes.user_likes FROM stream WHERE post_id = 'ENTER_YOUR_POST_ID'
After running the query, you should get a result that looks this this:
{
"data": [
{
"likes": {
"user_likes": true
}
}
]
}
If the User likes the Post, the field user_likes will be true and false if the User has not liked the Post.
You can parse the result like this (pseudo code):
if (JOLikeStatus.has("likes")) {
JSONObject optLikes = JOLikeStatus.optJSONObject("likes");
if (optLikes.has("user_likes")) {
String getUserLikes = optLikes.getString("user_likes");
if (getUserLikes.equals("true")) {
String getLikeStatus = "true";
} else if (getUserLikes.equals("false")) {
String getLikeStatus = "false";
}
} else {
String getLikeStatus = null;
}
} else {
String getLikeStatus = null;
}
EDIT 2: To get the number (count) of total likes, modify the earlier query like this:
fql?q=SELECT likes.user_likes, likes.count FROM stream WHERE post_id = 'ENTER_YOUR_POST_ID'
I have a very basic ASP MVC application exposing a static list of publications (see code and result below).
Code:
public JsonResult Index()
{
List<Publication> list = new List<Publication>() {
new Publication() { Id = 1, Name = "War and Peace" },
new Publication() { Id = 2, Name = "Harry Potter" },
new Publication() { Id = 3, Name = "Cat in the Hat" }
};
return this.Json(list, JsonRequestBehavior.AllowGet);
}
Result:
[{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]
When I attempt to consume it in Android I get the following error:
04-15 12:00:57.331: W/System.err(209): org.json.JSONException: A JSONObject text must begin with '{' at character 1 of [{"Id":1,"Name":"War and Peace"},{"Id":2,"Name":"Harry Potter"},{"Id":3,"Name":"Cat in the Hat"}]
I can remove the starting [ and ending ] and it stops the error from appearing. The other option is to put the { publications: logic at the beginning of the android code, but that seems like it should already be there.
How can I update the code in the MVC application to produce a "ready to be consumed" version of JSON?
Any help is greatly appreciated.
First, you shouldn't modify your json string when received, because it may mess up with the parsing.
Second, your Json string is in array format because it starts with [ and ends with ]. So, instead of using JSONObject, you should use JSONArray.
I recommend to use GSON. It's simple to use, fast and accurate.