Facebook Feed - JS SDK - javascript

I am trying to create a user's feed on my page using Facebook JS SDK but I am having issues accessing the values of nested objects.
This is my code:
FB.api('/me/feed', function(response) {
alert(response.data);
});
The alert here will return [object Object]
The data object is this:
{
"data": [
{
"message": "Some message",
"id": "some ID",
"created_time": "2014-01-05T22:46:10+0000"
}
],
"paging": {
"previous": "Link",
"next": "Link"
}
}
I need to access the message part of the object but I don't know how.

Simply access the properties directly
FB.api('/me/feed', function(response) {
alert(response.data.message);
});

I had to use JSON after all
FB.api('/me/feed',{limit:10}, function(response){
var jsonText = JSON.stringify(response.data,["picture"]);
alert(jsonText);
});
This will return an array with all the values of 'picture'
This is the example output
[{"picture":"https://fbcdn-photos-d-a.akamaihd.net"},
{"picture":"https://fbcdn-photos-g-a.akamaihd.net"},
{"picture":"https://fbexternal-a.akamaihd.net"},{},
{"picture":"https://fbcdn-profile-a.akamaihd.net"}]

It looks likedata is an array with a single element, so to get message, you will want to use response.data[0].message

Related

What is wrong with my JSON output for a Slack Message payload?

I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.

Can't access nested json elements with javascript

I'm really stuck on how to access nested elements of a json response that I'm getting from my api. I validated the json and it shows as valid.
For instance, how do I access the numFound attribute? Here's my code that is not working:
$.ajax({
url: "/api/SearchAPI/infopop?id=" + songID,
datatype:"json",
method: "get"
}).done(function (data) {
var obj = JSON.parse(data);
alert(obj); /* This displays the entire json response
alert(obj.response.numFound) /* This does not work
alert(data.response.numFound) /* This does not work
Here's the response I'm trying to access
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"off",
"fl":"Name,Description,Keywords,ISRC,Instruments,Lyrics,Bpm,Vocal,Tempo,Key,TV_Genres,Music_Genres,length\r\n,Writers,profileImagePath\r\n,Publishers\r\n,songImagePath\r\n,Band_Styles",
"start":"0",
"callback":"?\r\n",
"fq":[
"id:00106c8c-7e21-4e75-80da-cdff8e6d3d44",
"publicflag:1",
"pubname:komposed"
],
"rows":"10",
"version":"2.2",
"wt":"json"
}
},
"response":{
"numFound":1,
"start":0,
"docs":[
{
"profileImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f557110f-4ad3-4353-a1b3-3ba70d52e8f0?sv=2014-02-14&sr=b&sig=Q3ywrwEa6URp%2FPCvK0Ngesza8PBhMEmE5ONeKhw8vE4%3D&st=2016-06-16T16:49:45Z&se=2066-06-16T16:54:45Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3Dredneck.jpeg"
],
"songImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f0c00dcd-69f9-42af-b236-4a53f0d78e76?sv=2014-02-14&sr=b&sig=oF0STMDddyuJiNZO%2BE78sYtbboC4ic%2Fl4bR5ESBFouE%3D&st=2016-06-16T16:48:59Z&se=2066-06-16T16:53:59Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3DTENSION%20LAST%20MAN.jpg"
],
"Name":[
"Bottle Service Tension"
],
"Description":[
"Cool crime scene track with a chill night club vibe"
],
"Bpm":[
90
],
"Vocal":[
"Acapella"
],
"Tempo":[
"Fast"
],
"Writers":[
"Justin Sirota|100.00|"
],
"Keywords":[
"club, crime, investigation, cool, lounge, pulse"
],
"TV_Genres":[
"Tension"
]
}
]
}
}
Just use obj.numFound. response is your data argument.
$.ajax({
...
}).done(function (response) {
alert(response.numFound)
...
Also, since you're telling jQuery (assuming this based on the code) that the response is of JSON type via datatype:"json", you don't need to do JSON.parse on it.
Turns out the issue was in my API. I was returning json as a string instead of an object. Once I did that, javascript was able to reference the json elements. Thanks for trying to help!

Retrieve json data in Angular controller

I'd like to get a couple of values out of a JSON file in my app controller.
I have a JSON file that looks something like this:
{
"login": [
{
"username": "admin",
"password": "admin"
}
],
"header": [
{
"subTitle": "Hello",
"color": "red"
}
]
}
I am attempting to retrieve a value like this:
app.controller('loginCtrl', function($http, $scope) {
data = $http.get('data.json');
console.log(data.login.username);
}
However, all I'm getting in the console is TypeError: Cannot read property 'username' of undefined.
data = $http.get('data.json');
data.then(function(result){
console.log(result.login[0].username);
});
Even though your javascript is synchronous,the call you make is always asynch
$http.get('data.json').then(function (response) {
console.log(response.data)
});
So in your terms javascript called the get function and before it returned with result it executed this console.log(data.login.username);
So you did not got the expected result

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance
stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE
This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.
You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

twitter typeahead 0.9.3 remote return URL and json object

in bootstrap 2, I used the following code to post a json object,
$('#typeahead').typeahead({
source: function (query, process) {
var URL = 'http://localhost:8080/autocomplete/search/';
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return $.getJSON(URL,
{ query: JSON.stringify(query)},
function (data) {
return process(data);
});
}
});
Now in twitter tyeahead 0.9.3 they have done away with the source concept and moved to a remote concept, but unfortunately I do no know how to work with it.
$(".typeahead").typeahead({
remote : {
url: 'http://localhost:8080/autocomplete/search/',
replace: function(uri, query) {
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return uri + JSON.stringify(query);
},
filter: function(response) {
return response.matches;
}
return process(resultList);
}
}
Unfortunately it doesn't work, how do I just post the JSON object rather than appending it to the string? Thanks.
In your original code you use $.getJSON. This will send a request (and expects json as result) to: http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D
To do the same for Twitter's Typeahead call your replace function of your remote data should return a valid url. In your function the ?query= part of the url is missing.
You will have to set: url: 'http://localhost:8080/autocomplete/search/?query=',
You also will have to urlencode you json input maybe.
Note: you will not need the line return process(resultList); You will have to use the filter function to convert your json results to valid data:
The individual units that compose datasets are called datums. The
canonical form of a datum is an object with a value property and a
tokens property.
you could use templates to style your dropdown results, see: http://twitter.github.io/typeahead.js/examples/
By default, the dropdown menu created by typeahead.js is going to look
ugly and you'll want to style it to ensure it fits into the theme of
your web page.
You will need the additional CSS from https://github.com/jharding/typeahead.js-bootstrap.css to style the default dropdown for Bootstrap.

Categories

Resources