I'm messing around with AJAX/JSON for a bit of practice, and I'm attempting to retrieve live data from TfL's (Transport For London) API pertaining to train line statuses.
Here is a snippet of the JSON data I am working with:
[
{
"$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
"id": "bakerloo",
"name": "Bakerloo",
"modeName": "tube",
"disruptions": [],
"created": "2018-10-05T11:35:58.573Z",
"modified": "2018-10-05T11:35:58.573Z",
"lineStatuses": [
{
"$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
"id": 0,
"statusSeverity": 10,
"statusSeverityDescription": "Good Service",
"created": "0001-01-01T00:00:00",
"validityPeriods": []
}
],
I am trying to retrieve the name of the of the line (called "name" in JSON data) and the current status (called "statusSeverityDescription" in the data"). The code below can retrieve the name, but I have no idea how to retrieve statusSeverityDescription as it appears to be held within {}'s within an array.
$.ajax({
type: 'GET',
url: 'https://api.tfl.gov.uk/line/mode/tube/status',
dataType: 'json',
success: function(data) {
$.each(data, function(key, value){
var line = value.name;
var status = value.lineStatuses[0];
$("#content").append("<tr><td>" + line + "</td>" + "<td>" + status + "</td></tr>");
});
}
})
Any help would be much appreciated.
Thanks.
You already have the status object, so you just need to access status.statusSeverityDescription.
Related
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);
}
I am attempting to retrieve, but not create, tasks from Asana using Google Apps Script.
Using the Asana API Explore, I have constructed a URL that returns the data I desire: https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=987654321987654&completed_since=2018-02-22&limit=100&workspace=456789123456
This URL returns the desired data, in the following format:
{
"data": [
{
"id": 147258369147258,
"assignee_status": "inbox",
"name": "An example task name"
},
{
"id": 963852741963852,
"assignee_status": "upcoming",
"name": "And second example task name."
},
//etc...
]
}
With that URL as a model, I have created a Personal Access Token and executed the following function within Apps Script:
function getTasks5() {
// Asana Personal Token
var bearerToken = "Bearer " + "asdf123456789asdf456789456asdf";
//Request
var request = {
data: {
opt_fields: ["name", "assignee_status"],
assignee: "987654321987654",
completed_since: "2018-02-22",
limit: "100",
workspace: "456789123456"
}
};
// Request options
var options = {
method: "GET",
headers: {
"Authorization": bearerToken
},
contentType: "application/json",
payload: JSON.stringify(request)
};
var url = "https://app.asana.com/api/1.0/tasks";
var result = UrlFetchApp.fetch(url, options);
var reqReturn = result.getContentText();
Logger.log(reqReturn);
}
Instead of returning the desired data as the aforementioned URL does, the function creates an unnamed task in Asana, which is undesirable. It also returns this response containing undesired data:
{
"data": {
"id": 123456789123456,
"created_at": "2018-02-22T20:59:49.642Z",
"modified_at": "2018-02-22T20:59:49.642Z",
"name": "",
"notes": "",
"assignee": {
"id": 987654321987654,
"name": "My Name Here"
},
"completed": false,
"assignee_status": "inbox",
"completed_at": null,
"due_on": null,
"due_at": null,
"projects": [],
"memberships": [],
"tags": [],
"workspace": {
"id": 456789123456,
"name": "Group Name Here"
},
"num_hearts": 0,
"num_likes": 0,
"parent": null,
"hearted": false,
"hearts": [],
"followers": [
{
"id": 987654321987654,
"name": "My Name Here"
}
],
"liked": false,
"likes": []
}
}
Is it possible to simply GET a list of tasks in the manner exemplified by my first JSON example above without creating a task, and without resorting to using OAuth? If so, what changes to the Apps Script function need to be made?
Alright, the problem was with the approach I was taking. Rather than format the request with a payload (which infers a POST request), I needed to structure it more traditionally as a GET request, like so:
var requestUrl = "https://app.asana.com/api/1.0/tasks?opt_fields=name,assignee_status&assignee=123456789123&completed_since=2018-02-22&limit=100&workspace=987654321987";
var headers = {
"Authorization" : "Bearer " + AUTH_TOKEN
};
var reqParams = {
method : "GET",
headers : headers,
muteHttpExceptions: true
};
Then I was able to perform:
UrlFetchApp.fetch(requestUrl, reqParams);
And obtain the data I was after.
How can i display the value of a specific variable stored in an JSON API array?
For e.g. how could i display the current Bitcoin price in USD in a specific wordpress post using coinmarketcaps JSON API (https://api.coinmarketcap.com/v1/ticker/bitcoin/)?
The API gives me the following output:
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "3351.98",
"price_btc": "1.0",
"24h_volume_usd": "1455740000.0",
"market_cap_usd": "55289274334.0",
"available_supply": "16494512.0",
"total_supply": "16494512.0",
"percent_change_1h": "0.55",
"percent_change_24h": "3.45",
"percent_change_7d": "17.52",
"last_updated": "1502145551"
}
]
I only need to display the value of "price_usd" tho.
I've tried to do it this way, but it didn't work:
<script>
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
</script>
Any help would be much appreciated!
You need to call the function to execute the request:
var btcPrice;
function UpdateBtcPrice(){
$.ajax({
type: "GET",
url: "https://api.coinmarketcap.com/v1/ticker/bitcoin/",
dataType: "json",
success: function(result){
btcPrice = result[0].price_usd;
},
error: function(err){
console.log(err);
}
});
}
UpdateBtcPrice();
You can try this code
<?php
//get data with api call
$response = file_get_contents('https://api.coinmarketcap.com/v1/ticker/bitcoin/');
$response = json_decode($response);
echo $response[0]->price_usd;//print the value
?>
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?
After inserting a node containing 2 properties into a Neo4j database, how do I extract the properties ("name" and "phone") from a REST API query response? My script for querying the database is:
<script>
function query_database()
{
var restServerURL = "http://localhost:7474/db/data"; //local copy on windows machine
$.ajax({
type:"POST",
url: restServerURL + "/cypher",
accepts: "application/json",
dataType:"json",
data:{
"query" : "start n = node(*) return n",
"params" : {}
},
success: function(data, xhr, textStatus){
//alert("query success!");
//process query results here
alert(JSON.stringify(data, null, 4));
},
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}//end of query database
The "alert(JSON.stringify(data, null, 4));" displays the following:
{
"columns": [
"n"
],
"data": [
[
{
"paged_traverse": "http://localhost:7474/db/data/node/3761/paged/traverse/{returnType}{?pageSize,leaseTime}",
"outgoing_relationships": "http://localhost:7474/db/data/node/3761/relationships/out",
"data": {
"phone": "123.456.7890",
"name": "jeff "
},
"traverse": "http://localhost:7474/db/data/node/3761/traverse/{returnType}",
"all_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/all/{-list|&|types}",
"all_relationships": "http://localhost:7474/db/data/node/3761/relationships/all",
"property": "http://localhost:7474/db/data/node/3761/properties/{key}",
"self": "http://localhost:7474/db/data/node/3761",
"properties": "http://localhost:7474/db/data/node/3761/properties",
"outgoing_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/out/{-list|&|types}",
"incoming_relationships": "http://localhost:7474/db/data/node/3761/relationships/in",
"incoming_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/in/{-list|&|types}",
"extensions": {},
"create_relationship": "http://localhost:7474/db/data/node/3761/relationships"
}
]
]
}
Much thanks,
Jeff
In your example, you'd get the name and phone from the response data object like this:
var name = data.data[0][0].data.name;
var phone = data.data[0][0].data.phone;
alert("Name is " + name + "\nPhone is " + phone);
JSFiddle here.