parsing JSON data with java script - javascript

I use Google plus API and get this data from it and get an error while parsing this JSON data
and here is the code I use to parse this data and get error as data object is tested and work fine and hold data as it appear in past 2 images
var allIems = data.items;
for (var element in allIems) {
document.getElementById('datafromapi').innerHTML +=
(" , published time :" + element.published +
" , last updated time :" + element.updated +
", complete url : " + element.url
);
var obj = element.object.attachments;
document.getElementById('datafromapi').innerHTML +=
(+"\nattachments of post :\n" +
" type : " +
obj[0].objectType +
" ,displayName of content : " +
obj[0].displayName +
" ,content URL : " +
obj[0].url +
" ,content data :" +
obj[0].image.url +
" ,content type : " +
obj[0].image.type +
" ,content height : " +
obj[0].image.height +
" ,content width : " +
obj[0].image.width +
"\n\n\n");
}
});
i got that error appear
Uncaught TypeError: Cannot read property 'attachments' of undefined

element values in
for (var element in allIems) {
are keys of allItems, which in this case are array indices. You have to address the actual array items like this:
var obj = allItems[element].object.attachments;
Your code element.object.attachments; tries to access property object of a number, which does not exist.
Since we know that allItems is an array, you could have written:
for (var i = 0; i < allIems.length; i++) {
var obj = allItems[i].object.attachments;

Javascript has a built in JSON parser you can use that takes in a string of the data and returns an object.
let jsonDataAsString = "{\"a\":1,\"b\":2}";
let jsonDataAsObject = JSON.parse(jsonDataAsString);
Then you can traverse through the data as an object, referencing properties using dot-notation
console.log(jsonDataAsObject.a); // 1
To be safe, you should be comparing properties to null before trying to use then
if(jsonDataAsObject.somePropery != null) {
// the property exists so you can access it here
}

Related

I am unable to get environment names from an array

I have an array in which the environment list is stored and from this list, I have to get all the environment names which I am unable to get right now. See below what I have tried and please help me out of this.
<script>
//${environmentList} is getting from backend i.e from modal class in which toString() method has stored with all its contents.
var envLength = `${environmentList}`.length;
var allEnv = `${environmentList}`;
console.log("All Environments : " + allEnv);
console.log("Length of environments : " + envLength);
for(let i = 0 ; i < envLength ; i++){
let all = `${allEnv[i].environmentName}`;
console.log("Environment Name : " + all[i]);
}
</script>
toString() method :
#Override
public String toString() {
return "EnvironmentModel [environmentId=" + environmentId + ", environmentName=" + environmentName
+ ", environmentDesc=" + environmentDesc + ", hostAddress=" + hostAddress + ", environmentURL="
+ environmentURL + ", configFileName=" + configFileName + ", configFilePath=" + configFilePath
+ ", companyId=" + companyId + ", createdBy=" + createdBy + ", createdAt=" + createdAt
+ ", lastUpdatedBy=" + lastUpdatedBy + ", lastUpdatedAt=" + lastUpdatedAt + ", elementFileName="
+ elementFileName + ", elementFilePath=" + elementFilePath + ", envStatus=" + envStatus + ", projectId="
+ projectId + ", project=" + project + "]";
}
OUTPUT:
All Environments :
[EnvironmentModel [environmentId=345, environmentName=MM_Env_1, environmentDesc=Environment_1, hostAddress=null, environmentURL=null, configFileName=SystemFile.xml, configFilePath=/env_files/MM_Env_1, companyId=1, createdBy=2, createdAt=2019-12-18 16:39:38.595, lastUpdatedBy=2, lastUpdatedAt=2019-12-18 16:42:13.259, elementFileName=ElementFile.xml, elementFilePath=/env_files/MM_Env_1, envStatus=1, projectId=null, project=[Project [projectName=Magic Matrix, projectDescription=Magic Matrix is a significant and robust tool of the Solitera Software Company., projectId=23]]], EnvironmentModel [environmentId=346, environmentName=MM_Env_2, environmentDesc=Environment_2, hostAddress=null, environmentURL=null, configFileName=soapAPI_request_GetLyrics.xml, configFilePath=/env_files/MM_Env_2, companyId=1, createdBy=2, createdAt=2019-12-18 16:43:10.59, lastUpdatedBy=2, lastUpdatedAt=2019-12-18 16:43:58.522, elementFileName=Element.xml, elementFilePath=/env_files/MM_Env_2, envStatus=1, projectId=null, project=[Project [projectName=Magic Matrix, projectDescription=Magic Matrix is a significant and robust tool of the Solitera Software Company., projectId=23]]], EnvironmentModel [environmentId=347, environmentName=TM_Env_1, environmentDesc=TM_Env_1, hostAddress=null, environmentURL=null, configFileName=showcasetestData.xml, configFilePath=/env_files/TM_Env_1, companyId=1, createdBy=2, createdAt=2019-12-18 16:44:33.783, lastUpdatedBy=2, lastUpdatedAt=2019-12-18 16:44:47.09, elementFileName=soapAPI_request_TempConvert.xml, elementFilePath=/env_files/TM_Env_1, envStatus=1, projectId=null, project=[Project ...
Length of environments : 2235
Environment Name : undefined
Use Jackson json parser in Java class and in javascript side use JSON.parse to change the string to JSON object.
On the javascript side you'll should understand that the variable environmentList is a string and the length of the string is 2235 chars. To access each property you'll have to parse the string and turn it into an object.
As you are not relying on JSON you need to use String.split or a regex matcher.
But the simpler solution would be to convert the Environment variables into a JSON format. As the type of the output from System.getenv() is a Map<string, string> you can try this solution to create a JSON structure: Converting Map<String,String> into json
After that you'll either write the json in a script tag in HTML so it get's parsed directly, or user JSON parse on the string of the above solution.

mongodb batch insert - Javascript not working

I want to insert bunch of records into a collection, but instead of document at a time I want to do it like a batch using "insertMany()". I wrote the script as follows:
var batch = [];
for (i=0; i<10; i++) {
names=["exam", "essay", "quiz"];
for (j=0;j<3;j++) {
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
if (mod i%3 == 0) {
batch = batch.slice(0, batch.lenght(-1));
db.scores.insertMany( batch )
batch=[];
}
}
}
The above code is not working. There are two issues: first, the array item have double quotes around them and second, the "slice" is not taking effect.
Need help in fixing the Javascript.
There are a couple of issues here:
the array item have double quotes around them
batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
You want to create an object rather than a string. batch = { student: i, type: names[j], score: ..} will create an object for you.
the "slice" is not taking effect
batch = batch.slice(0, batch.lenght(-1));
You've misspelled length, and length is a property rather than a function. batch.slice() will copy the array (but you're resetting it so it's not actually necessary).

Can't access (only) some of an object's properties (JavaScript)

I'm using firebase / AngularJS, but I think this is a plain JavaScript object structure problem in my opinion.
Signing in Facebook manually with firebase, I cannot get access to 4 specific properties that are inside the "result" object from the signInWithCredential process.
(console) Logging the "result" object, the 4 variables are in there indeed, I just cannot get direct access to them.
However, I can get access to all the other properties of the object, which turns this into a really weird bug.
Here is the code :
firebase.auth().signInWithCredential(credential).then(function(result){
// $localStorage.firebaseToken = result.providerData.stsTokenManager.accessToken;
var chatUserData = {};
var updates = {};
console.log("result str obj : " + JSON.stringify(result)); // defined
console.log("result str > uid is " + JSON.stringify(result.uid)); // defined
console.log("result str > displayName is " + JSON.stringify(result.displayName)); // defined
console.log("result str > photoURL is " + JSON.stringify(result.photoURL)); // defined
console.log("result str > email is " + JSON.stringify(result.email)); // defined
console.log("result str > emailVerified is " + JSON.stringify(result.emailVerified)); // defined
console.log("result str > isAnonymous is " + JSON.stringify(result.isAnonymous)); // defined
console.log("result str Provider Data " + JSON.stringify(result.providerData)); // array of objects - defined
console.log("result str > apiKey is " + JSON.stringify(result.apiKey)); // gets undefined
console.log("result str > appName is " + JSON.stringify(result.appName)); // gets undefined
console.log("result str > authDomain is " + JSON.stringify(result.authDomain)); // gets undefined
console.log("result str > stsTokenManager is " + JSON.stringify(result.stsTokenManager)); // gets undefined
chatUserData.username = result.displayName;
chatUserData.email = $localStorage.fb_data.data.email;
chatUserData.id = result.uid;
updates['/users/' + result.uid + "/"] = chatUserData;
firebase.database().ref().update(updates);
}).catch(function(error) {
console.log("Error! " + JSON.stringify(error));
});
And here is the object code from the console log :
which makes this into a weird bug because I know the object is there, and supposedly I'm accessing it right, but it just doesn't load. This is usually just a stupid mistake I made, but I just can't seem to find it.
(the facebook profile I have there is fake)
Hope you guys can help, Cheers.
I fixed this, turns out this is a kind of firebase-managed object, the way to correctly loop through it is using angular.foreach. And even that way is not the correct one.
I should have used user.getToken(), and I found it right in the documentation.
Firebase User Get Token

CRM Javascript: Getting Email Address of the Participant List

In CRM 2013 I'm writing a javascript to remove certain email participants that contains a specific email address (in my code below it's test#test.com).
I was told that the best way to do this is to remove the whole email participants and re-build it, because there is no good way of just removing a specific participant from the email (please correct me if there's a better way).
So first I get all of the party in the "to" field in the email. Then I push the 'satisfactory' participants into a new array. The participants that contain test#test.com email will not be pushed into this new array i.e. get dropped from the list.
However I'm having problem trying to get the email address value from the "toParty" list.
This doesn't seem to work and returning undefined instead. Here I'm going by the email's schema name which is 'EMailAddress1'. Trying 'emailaddress1' doesn't work either.
toParty[indxAttendees].EMailAddress1 --> doesn't work
Any ideas is greatly appreciated.
var toParty = Xrm.Page.getAttribute("to").getValue();
for (var indxAttendees = 0; indxAttendees < toParty.length; indxAttendees++) {
var partyListData = new Array();
if (toParty[indxAttendees].EMailAddress1 != "test#test.com")
{
//alert("Email address " + indxAttendees + " :" + toParty[indxAttendees].EMailAddress1); --> this will be undefined value
partyListData[indxAttendees] = new Object();
//get ID
partyListData[indxAttendees].id = toParty[indxAttendees].id;
alert("ID " + indxAttendees + " :" + toParty[indxAttendees].id);
//get Name
partyListData[indxAttendees].name = toParty[indxAttendees].name;
alert("Name " + indxAttendees + " :" + toParty[indxAttendees].name);
partyListData[indxAttendees].entityType = toParty[indxAttendees].entityType;
alert("Entity Type " + indxAttendees + " :" + toParty[indxAttendees].entityType);
}
Using oDataQuery works in this case. Just have to write different function for queue since the email address field is different in queue vs. contact/account.
if ((entityType == "contact") || (entityType == "account")) {
select = "$select=EMailAddress1&$filter=" + entityType.charAt(0).toUpperCase() + entityType.slice(1) + "Id eq guid'" + entityId + "'";
var entitySet = entityType.charAt(0).toUpperCase() + entityType.slice(1) + "Set";
XrmServiceToolkit.Rest.RetrieveMultiple(entitySet, select,
function (results) {
if (results.length > 0) {
result = results[0].EMailAddress1;
}
}, function (error) { alert(error); }, function onComplete() { }, false);
return result;
}

JSON parse issue for duplicate data?

I'm constructing a JSON based on certain values,
my code is as follows,
var txt = '{ \"' + 9837 + '\": "Cost-A", \"' + 8943 + '\": "Cost-B", \"' + 13917 + '\": "Cost-C", \"' + 13917 + '\": "Cost-D"}';
_obj = JSON.parse(txt);
The output I get in the console is,
Object {9837: "Cost-A", 8943: "Cost-B", 13917: "Cost-D"}
Cost-C has been skipped completely? or is there something trivial I'm missing? How can I solve this?
Javascript ojects cannot have duplicate keys. Hence it gets overwritten.
{ "9837": "Cost-A", "8943": "Cost-B", "13917": "Cost-C", "13917": "Cost-D"}
The parser would add the latest value of the key.

Categories

Resources