Cannot access children of JSON object - javascript

I have a JSON object musicianobj, an example of which I have pasted below:
{
id: "451026389391"
name: "John Frusciante"
type: "profile"
url: "http://open.spotify.com/artist/XXXXXXXXXXXXXX"
}
I got this from the Facebook API using the Javascript SDK. I can run console.log(musicianobj); which successfully prints the object to the log in Chrome, but console.log(musicianobj.name);, console.log(musicianobj[1]);, and console.log(musicianobj["name"]); all return undefined for no apparent reason. Any ideas?
Edit: code below.
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj["name"]); // Doesn't work
console.log(musicianobj.name); // Doesn't work
artistname = musicianobj[1]; // Doesn't work
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}

Have you decoded it? It seems it is still a string.
musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work

Got it working! I had to put a [0] after musicianobj. Apparently I don't know JSON as much as I'd like to. The working code is pasted below:
var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
var songname = data.data[0].data.song.title;
var artistname = "";
FB.api(data.data[0].data.song.id,function(trackdata){
var musicianobj = trackdata.data.musician;
console.log(musicianobj);
console.log(musicianobj[0]["name"]);
console.log(musicianobj[0].name);
artistname = musicianobj[0].name;
});
if(artistname.length <= 0){
alert("Error! Please try another friend.")
}
}
);}

Related

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Parse : Retrieving properties from an object that is related

So I am doing a query to bring back a list of records, these records have a link to the user that created the record. The link is to the object.
My query gets me the object but I cant then access the fields of that object (except of course ID)
query.equalTo("search", search);
query.include("user");
query.find({
success: function(Report) {
for (var i = 0; i < Report.length; i++) {
var test = Report[i].id;
query.get(test, {
success: function(result) {
var reportDescription = result.get("reportDescription");
var reportPicture = result.get("reportPicture");
var reportPosition = result.get("reportPosition");
var reportType = result.get("reportType");
var reportDate = result.get("createdAt").toLocaleString();
var reportSearchId = result.get("search").id;
var user = result.get("user")
console.log(user)
var reportSearchBy = user.username;
},
error: function(result, error) {
alert(error.message);
}
});
};
},
error: function(error) {
alert(error.message);
}
});
What am I doing wrong?
i tried to run similar code to what you did. when i tried to access with dot notation i get undefined but when i tried to get it with .get("fieldName") it works..
here is my code:
var FileTest = Parse.Object.extend("FileTest");
var query = new Parse.Query(FileTest);
query.include("user");
query.find().then(function(results){
var lastItem = results[results.length - 1];
if (lastItem){
var user = lastItem.get("user");
console.log(user.get("username"));
}
},function(error){
});
please notice that i also use Promise for better coding and in order to get the username i did lastItem.get("username")
so please try to replace user.username with user.get("username")
and see if it works.

Mailchimp Google sheet issue with the api key

All the variables are returning correct values but the the urlfetch response returns 403 or 401 (access denied).
First log output:
var payload = {
"apikey": API_KEY,
"filters": {
"sendtime_start": REPORT_START_DATE,
"sendtime_end": REPORT_END_DATE
}
};
Logger.log(payload );
Second log output:
var params = {
"method": "POST", //what MC specifies
"muteHttpExceptions": true,
"payload": payload,
"limit": 100
};
Logger.log(params);
Third log output:
var apiCall = function(endpoint) {
//issue with syntax here?
var apiResponse = UrlFetchApp.fetch(automationsList, params);
var json = JSON.parse(apiResponse);
Logger.log(apiResponse);
return json;
};
Automation API Call that is not working:
var automations = apiCall(automationsList);
var automationsData = automations.data;
for (var i = 0; i < automationsData.length; i++) {
// are these response parameters? are these specific values getting pulled from MC - these are the type of values i want?
var a = automationsData[i];
var aid = a.id; // identifies unique campaign *** does this have anything to do with the call function above - it used to be as cid b/c this was for campaigns before??
var emails_sent = a.emails_sent;
var recipients = a.recipients;
var report_summary = a.report_summary;
var settings = a.settings;
if (send_time) {
var r = apiCall(reports, cid); // why does this have cid? but the other one didn't??
var emails_sent = r.emails_sent;
var opens = r.opens;
var unique_opens = r.unique_opens;
var clicks = r.clicks;
var unique_clicks = r.unique_clicks;
var open_rate = (unique_opens / emails_sent).toFixed(4);
var click_rate = (unique_clicks / emails_sent).toFixed(4);
}
The for loop is not even gets executed because I get following error for automationsData:
TypeError: Cannot read property "data" from undefined. (line 82, file "Code")
The apiResponse there is somehow not working, any help is appreciated.
The problem is in how you set up your project in the Developers Console. Try to follow again the process here for you to verify if you already do it in the correct way.
You can also check the solution here in this SO question, he/she explained it here, why he/she get the same 401 and 403 error that you get.
As it turns out, I was using v3.0 for the Mailchimp api whereas I needed to use 2.0.

Object handling in Chrome/FF?

I have this code:
$('.gBook').click(function(){
var values = [];
var getDiff = $('#totalPrice').attr("data-value");
var i = 0;
$('td[data-check="true"]').each(function(){
var valueToPush = { };
valueToPush["price"] = $(this).attr("data-price");
valueToPush["id"] = $(this).attr("data-id");
valueToPush["diff"] = getDiff;
values.push(valueToPush);
i++;
});
var arrayToSend = {values};
$.post( '<?php echo PATH;?>ajax/updateRoom.php',arrayToSend, function(data){
if(data != "ERROR"){
$('#all-content').html(data).css("overflow-y","auto");
}else{
alert("ERROR");
}
});
});
In Chrome, this line gives an error var arrayToSend = {values}; (Uncaught SyntaxError: Unexpected token }) In Firefox everything is fine.
I guess it's because of the rather "loose" error handling of FF, but how am I doing it correctly?
I tried to initialize the object with var arrayToSend = new Object(); before the $.each, but that gives an empty array after POST.
Where is my mistake?
try this
var arrayToSend = {optionsChosen:values};
Then in php or whatever you use for data handling look for the POST variable optionsChosen.
What you did was try to make an Object with parameter array = nothing
You basically did this in your code. It doesn't take an expert to see whats wrong with this statement.
arrayToSend = new function() {
this.(new Array(1,2,3)); // This is cringeworthy if you see it like this.
}
In the example I gave it translates to this:
arrayToSend = new function() {
this.optionsChosen = new Array(1,2,3);
}

Code not getting expected values when reading URL parameters

I've been racking my brain about this and I can not figure out why this isn't working.
I have a link that looks like this:
http://exampledomain.com/page.html?var1=42&var2=hello
and page.html is calling a javascript page that says:
alert(var1);
alert(var2);
But when I test the page all I get is function Number() { [native code] }
Anybody know what I could be going wrong?
Use this function:
var GET = function(query){
var varsArray = [],
url = window.location.search.match(/[^\?\&]+/g),
vars = [];
for(var i=0;i<url.length;i++)
if(/\=/.test(url[i]))
vars.push(url[i]);
for(var i=0;i<url.length;i++){
var This = url[i].split('=');
varsArray[This[0]] = This[1];
}
return query ? varsArray[query] : (varsArray || '');
}

Categories

Resources