How to get JSON objects from web service response - html

I am very new to use web services, javascript, JSON technologies and I need to use a URL to get some data to use in my HTML file.
The url that I am trying to get value of is something like this.
the result of this url in browser is like below:
{
"transactionid": "asdf",
"status": 0,
"poilist": [
{
"id": 123,
"name": "some company",
"address": "address",
"latitude": 333333,
"longitude": 333333,
"distance": 4869
},
{
.... // lots of similar nodes to above
}
}
I need to get some properties of poilist list such as longitude, latitude etc. and use them in my HTML file which includes only Javascript and HTML codes.
I made some research on internet but couldn't find a appropriate example for my situation. I don't know where to start. Any help will be appreciated.
Thank you.

You could to it this way:
var url = 'http://www.locationbox.com.tr/locationbox/services?Key=key&Cmd=PoiSearch&Typ=JSON&Latitude=30&Longitude=30&Radius=10000&Brand=SomeBrand&Keyword=';
$('#test').on('click', function () {
$.ajax({
url: url,
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// work with the response
success: function (response) {
//response is an object. use it here
console.log(response); // server response
}
});
});
http://jsfiddle.net/hlapidez/sm64g/

Hope this helps for u.
Here poilist is an JsonArray.
So u have to iterate poilist and get poilist properties
javascript example
var response = "{ "transactionid": "asdf", "status": 0, "poilist": [ { "id": 123, "name": "some company", "address": "address", "latitude": 333333, "longitude": 333333, "distance": 4869 },... ";
var poiList = response.poilist;
for(var i=0;i<poiList.length;i++){
var name = poiList[i].name;
var id= poiList[i].id;
var lat = poiList[i].latitutde;
var long = poiList[i].longitude;
console.log(lat);
console.log(long);
}
This code will print all properties of poilist in browser's console.

I would start with jQuery, specificaly with jQuery.getJSON(). Read about it here.
If you haven't used jQuery and don't know how to use it. I would look at here first.
Very basic example of loading the data and showing them in console would look like this:
$(document).ready(function() {
var url = ""; //enter an url here
$.getJSON(url, function( data ) {
console.log(data);
});
});

Related

How can I get a specific response value from response body in postman

{
"Group": "4r3rwee",
"EventType": "string",
"EventId": "string",
"Payload": "{\"Id\":\"6fd04f93e22e44c98752e209c1b74b03\",\"Name\":\"Md. Sakibur Rahman\",\"Email\":\"sakibur.rahmandd773661#orbitax.com \",\"Phone\":\"string\",\"Title\":\"Add Contact\",\"Status\":1,\"ContactType\":0,\"CompanyId\":\"automation\",\"ProjectId\":\"\"}",
"Status": 1,
"Id": "57c9c52a645a40f5bed0562dbee7d13b"
}
How can I get Id value from the payload?
I am using this command, but it's not working
pm.test("Set Contacts ID", function () {
var jsonData = pm.response.json();
//console.log("Response Payload : " + jsonData.Payload.{jsonData.Id});
pm.environment.set("contactIds", jsonData.Payload.Id);
});
As per the request data shown in the question, param. Payload contains JSON string. So, you'd need to parse it first, to access the property as follows,
pm.test("Set Contacts ID", function () {
var jsonData = pm.response.json();
var payloadData = JSON.parse(jsonData.Payload); //parsed payload
console.log(payloadData.Id);
pm.environment.set("contactIds", payloadData.Id);
});

How to Retrieve (not create) Tasks from Asana using Apps Script & Personal Access Token

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.

Populating Google Map Markers from Node Mongodb model

I need some help to populate google map markers by using data on my Mongodb with NodeJS.
This is my Model Schema (models/listing.js):
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var listingSchema = new mongoose.Schema({
category: String,
title: String,
location: String,
latitude: Number,
longitude: Number,
url: String,
type: String,
type_icon: String
},
{ collection: 'listing' }
);
// Return Model
module.exports = restful.model('Listing', listingSchema);
When I use postman to GET /api/listing, this is what I have
[{
"_id": "57092ca64f43442f0bcd6a95",
"category": "services",
"title": "Musa 24 hours Printing",
"location": "16 Bali Lane, Singapore 189852",
"latitude": 1.3007598,
"longitude": 103.8588499,
"url": "http://www.musa-group.com/24hrsinternet/printing.html",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/HwiyMCK.png"
]},
{
"_id": "57092ca64f43442f0bcd6a96",
"category": "services",
"title": "Rocket Printers SG",
"location": "146 Jalan Bukit Merah, Singapore 160146",
"latitude": 1.2778769,
"longitude": 103.8308443,
"url": "http://www.rocketprinters-sg.com/",
"type": "Printing",
"type_icon": "assets/icons/media/text.png",
"gallery": [
"http://i.imgur.com/XPYgZ7a.jpg"
]
}]
On my index.ejs file, the markers are currently pulled from an items.json.txt file
<script>
var _latitude = 1.36080344;
var _longitude = 103.81565094;
var jsonPath = 'assets/json/items.json.txt';
// Load JSON data and create Google Maps
$.getJSON(jsonPath)
.done(function(json) {
createHomepageGoogleMap(_latitude,_longitude,json);
})
.fail(function( jqxhr, textStatus, error ) {
console.log(error);
});
// Set if language is RTL and load Owl Carousel
$(window).load(function(){
var rtl = false; // Use RTL
initializeOwl(rtl);
});
autoComplete();
</script>
How can I change the source from 'items.json.txt' to my 'Listing' database collection? Much appreciation for any help at all!
Assuming your JSON files has the same structure as the JSON returned by /api/listing, you can simply replace the URL of your JSON file by yourserver.com:XX/api/listing, assuming the server yourserver.com is running your API on port XX.
I suspect the jQuery.getJson method is just a wrapper around jQuery.get that adds parameters to the request such as an appropriate Content-Type header.

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

Insert post Blogger API failed in GAS

hi all iam trying insert post using GAS but failed.. can you tell me what im wrong... thx in advance....
here my code
`function sendHttpPost() {
var API_KEY = 'my api key';
var scope = "http://www.blogger.com/feeds/";
var oAuthConfig = UrlFetchApp.addOAuthService("blogger");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "486683248036684073"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
var options =
{
"contentType":"application/json",
"oAuthServiceName" : "blogger",
"oAuthUseToken" : "always",
"method" : "POST",
"payload" : payload
};
var respon = UrlFetchApp.fetch("https://www.googleapis.com/blogger/v3/blogs/486683248036684073/posts?key="+API_KEY, options);
and here is error message
Request failed for returned code 400. Server response: { "error": {
"errors": [ { "domain": "global", "reason": "parseError", "message":
"Parse Error" } ], "code": 400, "message": "Parse Error" } }
I believe you are trying to use oauth1 when oauth2 is required.
there already is a unanswered request about that here.
Implementing oauth 2 with Google app script is really a pain, so I made an attempt to build a library that could answer the need (dioxygen library) - it work a little bit like the oauth2 playground but it's less pretty.
With a little work you should be able to adapt it to your need with blogger.
I tried Harold's library, but after successfully retrieving OAuth token, I ended up with the same error.
But, when I issued the same JSON request as in my script through the API Explorer, it was processed:
https://developers.google.com/blogger/docs/3.0/reference/posts/insert
[UPDATE]
I am taking it back. This code works. I just replaced the payload variable and put the JSON request straight into URL fetch options. So there was some problem with passing that payload variable into options variable.
function testBlogger() {
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "YOUR_BLOG_ID"
},
"title": "New post",
"content": "With content..."
};
var options =
{
"method" : "post",
"headers" : { "Authorization" : "Bearer YOUR_ACTIVE_TOKEN"},
"contentType" : "application/json",
"payload" : '{ "kind": "blogger#post", "blog": { "id": "YOUR_BLOG_ID" }, "title": "New post", "content": "With content..." }'
};
try {
var result = UrlFetchApp.fetch(
"https://www.googleapis.com/blogger/v3/blogs/YOUR_BLOG_ID/posts",
options);
Logger.log(result);
} catch (e) {
Logger.log(e);
}
}