I have some json being returned from a jquery ajax function.
Here is an example of said json:
var b =
{
"SelectByUserResult": [{ "DateAdded": "/Date(1357300130930+0000)/", "Deleted": false, "FileExtension": "jpg", "Filename": "e5d1ee90-f3c0-4dd7-9996-d1725a1fc031.jpg", "Height": 768, "Id": 955, "IsBpMember": true, "OriginalFilename": "Tulips.jpg", "SessionId": "277d31bf-84e1-4678-ad66-e7b332936219", "Title": "New image", "TotalRecords": 16, "UserId": "ded98560-61d0-42f2-944e-30280d54e94b", "Width": 1024}]
}
I have other ajax functions which return similar json in a similar structure, the only difference is the object 'SelectByUserResult' might be changed to 'SelectByIdResult' or 'SelectByNameResult'.
So in my ajax function (in the success function) I would do this to access the json b.SelectByUserResult
I want to be able to access that object but without specifying the name (as it's not always known). How would I go about doing that? Thanks
My funny variant (maybe not the best). It will return the first property of the object, I guess this is what you need.
function getFirstProp(obj) {
for (var i in obj) return obj[i];
}
Usage:
console.log(getFirstProp(b));
Related
I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
JSON.parse(x);
console.log(x.status);
Can anybody suggest something I may be doing wrong? Thank you!
JSON.parse Return value
The Object, Array, string, number, boolean, or null value
corresponding to the given JSON text. - MDN
You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
const parsedData = JSON.parse(x);
console.log(parsedData.status);
or you can directly get value one time after parsed as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
console.log(JSON.parse(x).status);
I am having trouble trying to present an array of objects on the tooltip of an Anychart.js map. I understand that we can access the dataset by doing something like: %[name of property in data set]. My data set has the following form:
{
"country": "Austria",
"id": "AT",
"continent": "Europe",
"songs": [
{
"rank": 33,
"title": "Stuck with U (with Justin Bieber)",
"artists": "Ariana Grande, Justin Bieber",
"album": "Stuck with U",
"explicit": 0,
"duration": "3:48"},
{
"rank": 34,
"title": "Late Night",
"artists": "Luciano",
"album": "Late Night",
"explicit": 0,
"duration": "3:20"
},
... more objects
]
}
}
If I wanted to access the Country property I would simply add it to the tooltip by doing:
tooltip.format("Country: " + {%country});
The issue is when trying to access an array of objects, I have tried different variations and none of them worked. Trying to show the title of every song:
tooltip.format({%songs}.{%title});
tooltip.format({%songs.%title});
tooltip.format({%songs}[{%title}]);
I also saw in the documentation that we can send a function as argument so I tried the following where I would concatenate every title of the collection but did not succeed either:
tooltip.format(function() {
let concatenated = '';
this.songs.forEach(song => {
concatenated += song + ' ';
});
return concatenated;
});
I would really appreciate your help guys.
String tokens do not support nested objects/properties. But you can use the callback function of the formatted to get access to songs. The context prototype includes getData() method provides that. Like this:
series.tooltip().format(function() {
console.log(this.getData('songs'));
return 'tooltip';
});
For details, check the live sample we prepared.
In case any one else is looking for a solution to this answer. I figured out how to loop through an embed array, and call on specific information.
chart.edges().tooltip().format(function () {
var format = ''
var songs = this.getData('songs');
songs.forEach(function (data, builtin, dom) {
format = '<p>'+data['title']+' by '+data['artists']+' </span></p>' + format
});
console.log(format)
return format
});
I'm currently using the fixture file to make sure it will be easier to call the right value.
cy.fixture('latestLead.json').then(function (lead) {
this.lead = lead
})
My son file is the following:
{
"status": 0,
"result": {
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Lead",
"url": "/services/data/v51.0/sobjects/Lead/111111111"
},
"Id": "111111111",
"Name": "Andres Latest Test"
}
]
}
}
The way that I'm trying to get the right value is the following:
cy.get(".gLFyf").type(this.lead.result.records.Id)
I'm able to get totalSize or done from the result object, but I'm not able to get any other value higher than that object. How can I get the Id value from the records Array?
You can access an array item (in your case it's the object) using the index position (in your case it's zero)
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
try this
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
Let's imagine that we have sap.m.UploadCollection and we bind the data to this collection which is done like this:
bind: function () {
this._oUploadCollection.bindAggregation("items", {
path: "/attachments",
factory: jQuery.proxy(this._bindUploadCollectionItem, this)
});
},
The example of the binding data is here:
{
"attachments": [
{
"size": 123,
"filename": "pdf.pdf",
"id": "pdfId"
},
{
"size": 440,
"filename": "text.txt",
"id": "textId"
}
],
"source":"personWhoAddedAttachments"
}
So, in _bindUploadCollectionItem I successfully can get size, filename and id by oContext.getProperty("nameOfParameter"), but cannot get source:
_bindUploadCollectionItem: function (sID, oContext) {
return new sap.m.UploadCollectionItem({
"id": oContext.getProperty("id"),
"fileName": oContext.getProperty("filename"),
"attributes": [
{
"title": "author",
"text": oContext.getProperty("../source") // <- problem
}]
});
},
So, because I bind attachments it is kind of clear that I could not get source, but how to reach it if I need it?
It depends a little on what property of the model you want to get to. If it is really like you described it and the target property is in the /source absolute model path, then the easiest way of getting it inside the factory function is by using: oContext.getModel().getProperty("/source").
If you need something which is inside a collection (and somehow depends on the current context), you can achieve an effect similar to the .. path construct that you tried by using something along the lines:
var sPath = oContext.getPath(),
sParent = sPath.substring(0, sPath.lastIndexOf("/")),
sText = oContext.getModel().getProperty(sParent + "/source");
return new sap.m.UploadCollectionItem({
"id": oContext.getProperty("id"),
"fileName": oContext.getProperty("filename"),
"attributes": [{
"title": "author",
"text": sText
}]
});
You basically obtain the parent object path by searching for the last / inside the path. You can apply this repeatedly (or use a split, pop some elements, followed by a join) to get to the ancestors (e.g. parent of parent).
I have the following JSON object:
[
{
"comments": [
{
"created_at": "2011-02-09T14:42:42-08:00",
"thumb": "xxxxxxx",
"level": 1,
"id": 214,
"user_id": 41,
"parent_id": 213,
"content": "<p>xxxxxx</p>",
"full_name": "xx K"
},
{
"created_at": "2011-02-09T14:41:23-08:00",
"thumb": "xxxxxxxxxxxxx",
"level": 0,
"id": 213,
"user_id": 19,
"parent_id": null,
"content": "<p>this is another test</p>",
"full_name": "asd asd asd asd asd"
}
],
"eee1": "asdadsdas",
"eee2": "bbbbb"
}
]
This is coming from a $.ajax request, in success I have....
success: function (dataJS) {
console.log(dataJS);
console.log(dataJS[eee1]);
console.log(dataJS.comments);
}
Problem is I can't get access to the items in the JSON object, even though dataJS does show correctly in the console. Ideas?
That's because your base object is an array as well.
console.log(dataJS[0].comments[0]);
I suspect that would work
the JSON you have coming back is actually an array itself, so...
dataJS[0].comments[0].created_at
will be 2011-02-09T14:42:42-08:00, etc...
Both dataJS and comments are arrays, and need indexes to access the appropriate elements.
The object being returned is itself an array, so to get to the first comment (as an example), this is how you would access it:
dataJS[0].comments[0]
console.log(dataJS);
console.log(dataJS[0].eee1);
console.log(dataJS[0].comments[0]);
Do something like this:-
var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}];
var created_at = dataJS[0].comments[0].created_at;
Yes, as others have stated, the JSON is actually an Array (of a single Object). So you will need to reference an index.
Interestingly enough (to me), your result string does validate successfully as JSON. I assumed until now, that to be valid JSON, it had to be an Object (ie, {}).
JSON must be interpreted with eval function (after the obvious sanitization, see security considerations of eval). Are you sure your framework does that for you?