BackboneJS How to fetch specific value from API JSON file - json

I have a BackboneJS Application where I want to fetch a specific value from a JSON API.
The JSON file has this structure:
"data": {
"title": "some title",
"startDate": "some start date",
"endDate": "some enddate",
"description": "description blablabla ",
"contest_id": 10,
}
I want to fetch the "contest_id". So I have this Backbone Model:
CompetitionQuestion.CompetitionQuestionModel = Backbone.Model.extend({
url: function() {
return App.APIO + '/i/contest/' + this.contest_id;
},
defaults: {
"data": []
}
});
This gives me /i/contest/undefined Why is that?? I cant do:
return App.APIO + '/i/contest/' + this.data.contest_id;
Can someone tell me what I'm doing wrong?

Related

Modify Json to use into React beautiful Drag and drop

I am using this library for react drag and drop functionality. However, my json is in this format
[
{
"id": "5f7",
"itemName": "ABC"
},
{
"id": "780",
"itemName": "CRD"
},
]
However, all the tutorial points, i will need something like this:
[
'item1': {
"id": "5f7",
"itemName": "ABC"
},
'item2': {
"id": "780",
"itemName": "CRD"
}
]
So how can i modify my json and add id for drag and drop functionalities. Even if there is any other way of achieving this then i really appreciate that.
You can do this with plain javascript, loop through your item's array with map() and create a new array that encapsulates the item, see following example:
var currentArray = [{
"id": "5f7",
"itemName": "ABC"
},
{
"id": "780",
"itemName": "CRD"
}];
var result = "", sep = "";
currentArray.forEach((el, i) => {
result += sep + "\"item" + (i+1) + "\"";
result += ": " + JSON.stringify(el);
sep = ", ";
});
console.log(JSON.parse("{" + result + "}"));

InlineQueryResultArticle of answerInlineQuery in Telegram Bot API with Google Apps Script

I'm using google apps script for Telegram Bot API & I'm having problem with InlineQueryResultArticle in answerInlineQuery method.
function answerInlineQuery(iqid, result){
var data = {
method: "post",
payload: {
method: "answerInlineQuery",
inline_query_id: iqid,
results:JSON.stringify(result)
}
}
}
Here is the format of result :-
var result= {
InlineQueryResultArticle:[
{type:'article',id: iqid, title:"RESULT 1", input_message_content:"TEXT 1"},
{type:'article',id: iqid, title:"RESULT 2", input_message_content:"TEXT 2"}
]
};
answerInlineQuery(iqid, result);
I have turned on Inline Mode in #BotFather. My bot is also receiving inline queries and for every request I can see my inline query id properly & I can also see the result receiving as [object Object].
But, the problem is I'm not getting any results.
REF: In answerinlinequery, the results should be a JSON-serialized array of results for the inline query using any of these results.
Can anyone point out where am I going wrong ?
The id field for a InlineQueryResultArticle must be unique for each result. However you are setting the id as iqid for both results.
You should replace them with custom ids.
var result= {
InlineQueryResultArticle:[
{type:'article',id: "1", title:"RESULT 1", input_message_content:"TEXT 1"},
{type:'article',id: "2", title:"RESULT 2", input_message_content:"TEXT 2"}
]
};
After many attempts I found solution:
Here there are an inline answer with three results
****Be careful :change value of document_file_id with a sample file_id from your bot else you will see an error
//your bot token placed here
const token = "";
tgmsg('answerInlineQuery', {
"inline_query_id": update['inline_query']['id'],
"results": JSON.stringify([
//inline result of an article with thumbnail photo
{
"type": "article",
"id": "1",
"title": "chek inline keybord ",
"description": "test ",
"caption": "caption",
"input_message_content": {
"message_text": "you can share inline keyboard to other chat"
},
"thumb_url": "https://avatars2.githubusercontent.com/u/10547598?v=3&s=88"
},
//inline result of an article with inline keyboard
{
id: "nchfjdfgd",
title: 'title',
description: "description",
type: 'article',
input_message_content: {
message_text: "inline is enabled input_message_content: {message_text: message_text}message_text"
},
reply_markup: {
"inline_keyboard": [
[{
"text": "InlineFeatures.",
"callback_data": "inline_plugs_1118095942"
}],
[{
"text": "OtherFeatures.",
"callback_data": "other_plugs_1118095942"
}]
]
}
},
//inline result of a cached telegram document with inline keyboard
{
id: "nchgffjdfgd",
title: 'title',
description: "description",
//change this on with the value of file_id from telegram bot api
document_file_id: "BQACAgQAAxkBAAIBX2CPrD3yFC0X1sI0HFTxgul0GdqhAALjDwACR4pxUKIV48XlktQNHwQ",
type: 'document',
caption: "caption ghh hhdd",
reply_markup: {
"inline_keyboard": [
[{
"text": "InlineFeatures.",
"callback_data": "inline_plugs_1118095942"
}],
[{
"text": "OtherFeatures.",
"callback_data": "other_plugs_1118095942"
}]
]
}
}
])
})
function tgmsg(method, data) {
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(data)
};
var responselk = UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/' + method, options);
}

Parsing json_callback response from server Angular 4

Using Angular 4, I sent a get request to this url https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK&format=json&tagmode=all&tags=test
with following code,
this.http.get('https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=JSON_CALLBACK', {
params: { format: 'json', tagmode: 'all', tags: query }
})
.subscribe(data => {
console.log(data);
});
The response I get is in the following format, wrapped as a method argument.
JSON_CALLBACK({
"title": "Recent Uploads tagged test",
"link": "https:\/\/www.flickr.com\/photos\/tags\/test\/",
"description": "",
"modified": "2018-02-04T14:51:42Z",
"generator": "https:\/\/www.flickr.com",
"items": [
{
"title": "Desktop2018-02-04-14_39_44.jpg",
"link": "https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/",
"media": {"m":"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg"},
"date_taken": "2018-02-04T06:51:42-08:00",
"description": " <p><a href=\"https:\/\/www.flickr.com\/people\/besnaveld\/\">besnaveld<\/a> posted a photo:<\/p> <p><a href=\"https:\/\/www.flickr.com\/photos\/besnaveld\/28298869359\/\" title=\"Desktop2018-02-04-14_39_44.jpg\"><img src=\"https:\/\/farm5.staticflickr.com\/4769\/28298869359_e932760377_m.jpg\" width=\"240\" height=\"135\" alt=\"Desktop2018-02-04-14_39_44.jpg\" \/><\/a><\/p> ",
"published": "2018-02-04T14:51:42Z",
"author": "nobody#flickr.com (\"besnaveld\")",
"author_id": "154665852#N05",
"tags": "test booth"
} ]
})
How can I extract the data inside this JSON_CALLBACK function argument?
based on filckr document simply add
nojsoncallback=1 -> {...}
jsoncallback=wooYay -> wooYay({...});
to your request to get it right . then your url should be :
https://api.flickr.com/services/feeds/photos_public.gne?nojsoncallback=1&format=json&tagmode=all&tags=test

how to retrieve values from JSON object and authenticate using google-plus:0.1 plugin

I am using google-plus:0.1 plugin in a Grails Application to enable login using Google+ ,I have successfully logged in and I am getting JSON object back.
Inside plugin there is a code where they are turning JSON string to JSON object and returning back to me.
This is the code inside a plugin:-
public Person getCurrentUserProfile() {
Person person
try {
URL url = new URL("https://www.googleapis.com/plus/v1/people/me?access_token=${this.accessToken}")
def jsonString = JSON.parse(url?.text)
println "URL : " + url.toString()
println "JSON : " + jsonString
person = Person.parseJSONForPerson(jsonString)
} catch (GooglePlusException e) {
e.printStackTrace()
}
return person
}
From here I am getting JSON object back
Json string printed in console is:-
URL : https://www.googleapis.com/plus/v1/people/me?access_token=ya29.lgFPSagK5lQ8l19hWuxra8AxsXzZjxlbCetP-aWpUHbq2_djrdvj-3XMFMEgl9r4WfaiLvo7Q3RfJQ
JSON : [etag:"RqKWnRU4WW46-6W3rWhLR9iFZQM/eUT2aym4R39YBu_ra8ZlhztXJ6w", organizations:[[startDate:1995, title:Science, primary:false, name:St.Joseph's Convent, endDate:2008, type:school]], image:[isDefault:false, url:https://lh5.googleusercontent.com/-kuh1_bl_8is/AAAAAAAAAAI/AAAAAAAAADA/ZZfY8ob2QrQ/photo.jpg?sz=50], isPlusUser:true, emails:[[value:kartiki.sahu#crowdera.co, type:account]], kind:plus#person, url:https://plus.google.com/102332421579091283598, id:102332421579091283598, verified:false, name:[familyName:Sahu, givenName:Kartiki], domain:crowdera.co, circledByCount:9, gender:female, displayName:Kartiki Sahu, objectType:person]
I am unable to fetch emails from the object which I am getting.
I tried fetching familyName as
person.name.familyName I got it's value,
but for givenName it is showing null and for emails and organisation it is showiing empty list like [].
My code :-
def code = request.getParameter("code")
String accessToken = accessTokenService.generateAccessToken(code)
googlePlusService.accessToken = accessToken
def person = googlePlusService.getCurrentUserProfile()
Please help.
You can get value like this .
String str="""{
"kind": "plus#person",
"etag": "\\"RqKWnRU4WW46-6W3rWhLR9iFZQM/eUT2aym4R39YBu_ra8ZlhztXJ6w\\"",
"gender": "female",
"emails": [
{
"value": "kartiki.sahu#crowdera.co",
"type": "account"
}
],
"objectType": "person",
"id": "102332421579091283598",
"displayName": "Kartiki Sahu",
"name": {
"familyName": "Sahu",
"givenName": "Kartiki"
},
"url": "https://plus.google.com/102332421579091283598",
"image": {
"url": "https://lh5.googleusercontent.com/-kuh1_bl_8is/AAAAAAAAAAI/AAAAAAAAADA/ZZfY8ob2QrQ/photo.jpg?sz=50",
"isDefault": false
},
"organizations": [
{
"name": "St.Joseph's Convent",
"title": "Science",
"type": "school",
"startDate": "1995",
"endDate": "2008",
"primary": false
}
],
"isPlusUser": true,
"circledByCount": 9,
"verified": false,
"domain": "crowdera.co"
}
"""
def jsonString = new JsonSlurper().parseText(str)
render jsonString.emails.value
}
I am getting output as a following list .
['kartiki.sahu#crowdera.co']
def code = request.getParameter("code")
String accessToken = accessTokenService.generateAccessToken(code)
URL url = new URL("https://www.googleapis.com/plus/v1/people/me?
access_token=${accessToken}")
def jsonString = JSON.parse(url?.text)
println "URL : " + url.toString()
println "JSON : " + jsonString
println "emails "+jsonString.emails.value[0]
println "name "+jsonString.name.givenName + " " +
jsonString.name.familyName

retrieving data using Ember

as I go deeper into EmberJS, I got into this context where I need to use HTTP request. As a start, I tried to retrieve JSON data so I made a test page that returns JSON and I also verified that it is in JSON by deserializing it. No errors were encountered but there is no output at all. Below are the details of my code
application.js
App = Ember.Application.create({});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest/testApi.aspx'
});
event.js
App.Event = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string')
});
router.js
App.Router.map(function () {
this.resource('events', {path: '/'});
});
App.EventsRouter = Ember.Route.extend({
model: function () {
return App.Event.find();
}
});
JSON output from host
{ "events": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
HTML
<script type="text/x-handlebars" data-template-name="events">
this is an example
{{#each e in model}}
<label>{{e.title}}</label><br />
{{/each}}
</script>
what could possibly be missing in my code? comments, opinions, suggestions are greatly appreciated
Looks like the return JSON is wrong.. it should be singular:
{ "event": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
When you do a find with Ember Data it should have the model name:
this.store.find('event') So Ember-data know where the return map to.
This will generate a URL http://host:port/event
If you are changing host it should just be the base URL you are changing and not absolute. So in your case:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest'
});
Then the URL will become http://172.19.20.30/EmberTest/events