unable to call json nested object image properties - json

in my case i am unable to call properties from a nested image object properties.below is my code. I have to print price and image title on html page. I really dont knw where i am wrong. Any help will be helpful.
how i called data :
const singerDetails = JSON.parse(xhr.responseText);
for (let i = 0; i < singerDetails.abc.length;enter code here i++) {
console.log(singerDetails.abc[i].price);
}
but what should i do for image object ? i tried
console.log(singerDetails.abc[i].image.title); but it gives error ..
Json File :
{
"abc": [
{
"price": 9,
"tea": "black",
},
{
"image": {
"alt": "hi i m alt",
"title": "i am tittle",
},
"price": 10,
"tea": "green",
},
{
"price": 19,
"tea": "black",
},
{
"image": {
"alt": "hi i m alt2",
"title": "i am tittle2",
},
"price": 10,
"tea": "green",
}
]
}

delete last comma in each of obj properties/
JS Bin code here
{"price": 19,"tea": "black"}
...

Related

Postman accessing child objects in Json in a Test

I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.

Filtering a nested json for a particular flied and returning adjacent member in ruby

I have an API response of the following structure
{
"id": "123342-123412",
"data": [
{
"id": "ace123",
"name": "Tom",
"files": [
{
"color": "yellow",
"file_id": "245"
},
{
"color": "red",
"file_id": "233"
}
]
},
{
"id": "asd123",
"name": "Jerry",
"files": [
{
"color": "red",
"file_id": "210"
},
{
"color": "green",
"file_id": "221"
}
]
},
{
"id": "acs123",
"name": "Barbie",
"files": [
{
"color": "green",
"file_id": "201"
}
]
}
]
}
I am new to ruby, I want to filter out all file ids with the color red, what's the better way of doing it rather than iterating through the whole JSON using
data.each do | object|
# individual element search code
end
I am using ruby version 2.6
The single line version that comes to my mind is:
json[:data].map {|d| d[:files] }.flatten.select {|f| f[:color] == 'red' }.map {|f| f[:file_id] }
=> ["233", "210"]
But this iterates multiple times (one for every method call), not to mention it looks kind of cryptic to me.
Personally I would prefer a verbose version, where it's clearly stated how's getting the values:
file_ids = []
json[:data].each do |data|
data[:files].each do |file|
next if file[:color] != 'red'
file_ids << file[:file_id]
end
end
file_ids.uniq # In case you have duplicates
But is up to you what to use.

How to retrieve nested JSON values

I have the fallowing JSON object and I want to take the value of Microsoft.VSTS.Scheduling.RemainingWork
[
{
"id": 13,
"rev": 12,
"fields": {
"System.Id": 13,
"Microsoft.VSTS.Scheduling.RemainingWork": 32,
"Microsoft.VSTS.Scheduling.CompletedWork": 20
},
"url": "https://dev.azure.com/.../_apis/wit/workItems/13"
}
]
I am able retrieve data until some point:
console.log("object of json : ",result);
console.log("result[0] : ", result[0])
console.log("result[0].fields : ", result[0].fields)
The console output is,
But I this is not working result[0].fields.Microsoft.VSTS.Scheduling.RemainingWork
You can access data like an associative array :
result[0].fields['Microsoft.VSTS.Scheduling.RemainingWork']
You need to use
result[0].fields["Microsoft.VSTS.Scheduling.RemainingWork"]
Basically when you use
result[0].fields.Microsoft.VSTS.Scheduling.RemainingWork
each time you use a ".", you are trying to get the value from a nested object, like this -
[
{
"id": 13,
"rev": 12,
"fields": {
"System.Id": 13,
"Microsoft": {
"VSTS": {
"Scheduling": {
"RemainingWork": 32
}
}
},
"Microsoft.VSTS.Scheduling.CompletedWork": 20
},
"url": "https://dev.azure.com/.../_apis/wit/workItems/13"
}
]
which is not correct since that is not the way your data is structured.

How to dynamically add object inside json array?

I'm trying to dynamically add an object inside every object which is present in my json array. But I'm unable to do so. My object is getting appended at the end of json which is not what I want.
jsonArray:any=[
{
"id": 1000,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment",
"postId": 1
},
{
"id": 3,
"body": "some comment",
"postId": 1
}
]
selectFLag:any={"selected":"true"}
temArray:any;
learnJSONPArse()
{
for (var i = 0; this.jsonArray.length > i; i++)
{
Alert(this.jsonArray.length)
}
}
this.jsonArray.push(this.selectFLag)
-----expected output is
[
{
"id": 1000,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 2,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 3,
"body": "some comment",
"postId": 1,
"selected":"true"
}
]
You're question is a little unclear, but it sounds like you want to map each item in your array to a new item. The new item is the same as the old one, but assigned an additional property.
If so, something like this could work for you:
const objToAppend = { selected: true };
jsonArray.map(item => Object.assign(item, objToAppend));
Refs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

How to get response (array of json) and put it in my html component in Angular 4

I am trying to get the array data in a JSON response. The following is my JSON response and I need to get all data to my html tags in component.
{
data : {
"topLikedMedia" : [
{
"id": "1546567845943506613_3718981156",
"type": "image",
"user": {
"id": "3718981156",
"username": "agoramonitor",
"full_name": "AgoraMonitor",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/18809269_476795959342067_7353566623065702400_n.jpg"
},
"tags": [
"instagramers",
"content",
"socialmedia",
"marketing",
"branding",
"instagram"
],
"location": null,
"comments": {
"count": 2
},
"formatted_comments_count": "2",
"created_time": "1498585275",
"formatted_time": "Tue, Jun 27, 2017 7:41 PM",
"diff_humans_time": "4 months ago",
"link": "https://www.instagram.com/p/BV2g0MGgPa1/",
"likes": {
"count": 154
},
"formatted_likes_count": "154",
"images": {
"thumbnail": {
"width": 150,
"height": 150,
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/c244.0.591.591/19533988_862713503881059_8677706625265434624_n.jpg"
},
"low_resolution": {
"width": 320,
"height": 175,
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/19533988_862713503881059_8677706625265434624_n.jpg"
},
"standard_resolution": {
"width": 640,
"height": 350,
"url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19533988_862713503881059_8677706625265434624_n.jpg"
}
},
"caption": "Whether you want to drive leads to your homepage or encourage customer engagement ",
"userHasLiked": false,
"filter": "Normal"
}
],
}
I have the temp of this output and I need to receive this response and distribute it on its own tags and i dont know how
First solution, the Angular way :
getTopLiked() {
this._dashboardService.getTopPosts()
.subscribe(res => {
// Get your data in your component's variable
this.data = res.json();
});
}
In your HTML
<div *ngIf="data">
<div *ngFor="let liked of data.topLikedMedia">
<p>ID : {{liked.id}}</p>
<!-- And you do every other field like that -->
</div>
</div>
Second solution, the old Javascript way
getTopLiked() {
this._dashboardService.getTopPosts()
.subscribe(res => {
this.createMarkup(res.json());
});
}
createMarkup(data: Object) {
this.markup = '';
for (let liked of data.topLikedMedia) {
this.markup += `<p>ID : ${liked.id}</p>`;
// add the other fields like that
}
}
In your HTML
<div *ngIf="markup">
<div [innerHTML]="markup"></div>
</div>