Javascript: Loop through nested objects and arrays - javascript

I have an server response with data which has the structur as you can see in the codesnippet.
My goal is to iterate through each consent and add the channels
The data from the response:
[
{
"consents": [
{
"channels": [
{
"granted": true,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": false,
"id": "phone",
"title": "Telefon"
},
{
"granted": false,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T16:03:25.753Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T16:03:25.778Z",
"id": "1b9649a6-d8de-45c6-a0ae-a03cecf71cb5",
"updatedAt": "2018-03-08T16:03:25.778Z",
"username": "demo-app"
},
{
"consents": [
{
"channels": [
{
"granted": true,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": true,
"id": "phone",
"title": "Telefon"
},
{
"granted": true,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T14:51:52.188Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T14:51:52.208Z",
"id": "cf550425-990e-45ef-aaee-eced95d8fa08",
"updatedAt": "2018-03-08T14:51:52.208Z",
"username": "demo-app"
},
{
"consents": [
{
"channels": [
{
"granted": false,
"id": "sms",
"title": "SMS/MMS"
},
{
"granted": true,
"id": "email",
"title": "E-Mail"
},
{
"granted": true,
"id": "phone",
"title": "Telefon"
},
{
"granted": false,
"id": "letter",
"title": "Brief"
}
],
"client": "App",
"configId": "99df8e86-2e24-4974-80da-74f901ba6a0d",
"date": "2018-03-08T14:48:27.024Z",
"granted": true,
"name": "bestandsdaten-alle-produkte",
"version": "1.0.0",
"versionId": "bd002dcd-fee6-42f8-aafe-22d0209a0646"
}
],
"createdAt": "2018-03-08T14:48:27.054Z",
"id": "7fc1f087-2139-4494-bad7-161b0c6231a9",
"updatedAt": "2018-03-08T14:48:27.054Z",
"username": "demo-app"
},
]
The way i go is the following. But i need a way to append the channels to each Consent. Is there a way to solve this?
consentsList.forEach((consent, index, array) => {
consent.consents.forEach((c) => {
Object.keys(c).forEach((key) => {
dd.content.push(
{
columns: [
{
text: `${key}: `, style: 'text'
},
{
text: c[key], style: 'text'
}
]
}
);
});
});
Consents.push(consent);
if (index !== array.length - 1) {
dd.content.push({
margin: [0, 0, 0, 5],
canvas: [{
type: 'line', x1: 0, y1: 5, x2: 595 - (2 * 40), y2: 5, lineWidth: 0.6
}]
});
}
});
I want to output the individual channels where channels is on the top of each entry

You can extract the titles using map. And concantanate them using join like this.
let value = "";
if(key === "channels"){
value = c[key].map(x => x.title).join(" ,");
}
else {
value = c[key];
}
columns: [
{
text: `${key}: `, style: 'text'
},
{
text: value, style: 'text'
}
]

I have written a piece of code, hope this is what you're looking for. It is not optimized, try to optimize at your will
var a = responseData;
a.forEach(function(items) {
var allChannels = [];
items.consents.forEach(function(innerItems){
innerItems.channels.forEach(function(value){
allChannels.push(value.title);
})
items.allChannels = allChannels.join();
})
});
console.log(a);

Related

Is it possible to print the label of the object instead the id in material ui DataGrid

So I have two tables in my database. I want a DataGrid UI to print all my columns except the categoryId I want to print a label instead (like in selection valueOptions) :
const columns: GridColDef = [
{
"field": "title",
"headerName": "Titel",
"width": 350,
"editable": true
},
{
"field": "categoryId",
"headerName": "Kategorie",
"width": 250,
"editable": true,
"type": "singleSelect",
"valueOptions": [
{
"value": "miv560972ynqzk9",
"label": "stuff 1"
},
{
"value": "1t7n08l9tfdwotn",
"label": "stuff 2"
},
]
}
]
const rows: GridRowsProp = [
{
"categoryId": "miv560972ynqzk9",
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": "1t7n08l9tfdwotn",
"title": "Test",
},
]
So I want something like this:
const rows: GridRowsProp = [
{
"categoryId": { value:"miv560972ynqzk9", label: "stuff1"},
"title": "Lineare Algebra Hausaufga",
},
{
"categoryId": { value: "1t7n08l9tfdwotn", label: "stuff2" },
"title": "Test",
},
]

How to structure and all data in the objective from Json at App script

The JSON data I am working on it. This is coming from Facebook ad API. This is being build for google data studio connector
{
"data": [
{
"adcreatives": {
"data": [
{
"actor_id": "8834759718540",
"id": "538"
}
]
},
"insights": {
"data": [
{
"ad_id": "34536578578",
"impressions": "89108",
"actions": [
{
"action_type": "comment",
"value": "02"
},
{
"action_type": "post",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-10T22:59:33+0600",
"id": "34536578578"
},
{
"adcreatives": {
"data": [
{
"actor_id": "7834759718970",
"id": "342"
}
]
},
"insights": {
"data": [
{
"ad_id": "238509545896206",
"impressions": "57803",
"actions": [
{
"action_type": "post_engagement",
"value": "2102"
},
{
"action_type": "page_engagement",
"value": "03"
}
],
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MAZDZD"
}
}
},
"created_time": "2022-06-11T22:59:33+0600",
"id": "238509545896206"
}
],
"paging": {
"cursors": {
"before": "dfgdfgdfgdfsdgdfgdfgdfgdfgdgdg",
"after": "yuyuyuyutyuytuyutytynfrgersggsgs"
}
}
}
Here is the JavaScript code I have used in google app script but it is showing error. I know it is totally wrong
var data = {data: parseData.data.map(({actions, ...rest}) => ({...rest,...Object.fromEntries(actions.map(({action_type, value}) =>[action_type, value]))}))};
console.log(data);
Output should be like the following way so that I can get all the data in objective
{
"data": [
{
"actor_id": "8834759718540",
"id": "538",
"ad_id": "34536578578",
"impressions": "89108",
"comment": "02",
"post": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10",
"created_time": "2022-06-10T22:59:33+0600"
},
{
"actor_id": "7834759718970",
"id": "342",
"ad_id": "238512373324806",
"impressions": "57803",
"post_engagement": "2102",
"page_engagement": "03",
"date_start": "2022-06-11",
"date_stop": "2022-07-10"
"created_time": "2022-06-11T22:59:33+0600"
}
],
"paging": {
"cursors": {
"before": "MAZDZD",
"after": "MQZDZD"
}
}
}
You can try the code below, but it only works if adcreatives.data and insights.data have only 1 element :
let part = data.data.map(item => ({
"actor_id": item.adcreatives.data.at(0).actor_id,
"id": item.adcreatives.data.at(0).id,
"ad_id": item.insights.data.at(0).ad_id,
"impressions": item.insights.data.at(0).impressions,
"comment": item.insights.data.at(0).actions.at(0).value,
"post": item.insights.data.at(0).actions.at(1).value,
"date_start": item.insights.data.at(0).date_start,
"date_stop": item.insights.data.at(0).date_stop,
"created_time": item.created_time
}));
let result = {
data: part,
paging: data.paging
}
console.log(result);

Big Json parsing in cypress, jsonPath usage

I'm new to cypress and I face a problem when trying to work with json responses. I am getting json with units structure(tree structure) and I need to get all the names from it.
I tried to use jsonpath dependenc and parse json using jp.query, but it doesn't works:
cy.request(*some request*).its('body').then((body) => {
let units = jp.query(body, "$..[?(#.type=='PROJECT')].name");
})
I'm getting obj needs to be an object Assertion error here
How to fix this or maybe there are any other ways to parse json in cypress?
JSON Sample:
[
{
"id": 2,
"name": "Solar",
"children": [
{
"id": 3,
"name": "Earth",
"children": [
{
"id": 4,
"name": "Moon",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
{
"id": 5,
"name": "Jupiter",
"children": [
{
"id": 6,
"name": "Io",
"type": "STREAM",
"active": true
},
{
"id": 7,
"name": "Ganymede",
"type": "STREAM",
"active": true
}
]},
],
"type": "PROGRAM",
"active": true
},
{
"id": 9,
"name": "Centaurus",
"children": [
{
"id": 10,
"name": "Alpha Centauri A",
"children": [
{
"id": 818,
"name": "Alpha Centauri Aa-2345",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
{
"id": 11,
"name": "Alpha Centauri B",
"children": [
{
"id": 12,
"name": "Alpha Centauri Bb",
"type": "STREAM",
"active": true
}
],
"type": "PROJECT",
"active": true
},
],
"type": "PROGRAM",
"active": true
}
]
add below 2 lines before jp.query()
body = JSON.stringify(body);
body = JSON.parse(body);
Depending on how the request/response is configured, you may have one of the following issues
response is a string
body is a string
there is no body
cy.request(*some request*)
.then(response => response.json())
.its('body')
.then(body => {
let units = jp.query(body, "$..[?(#.type=='PROJECT')].name");
})
or
cy.request(*some request*)
.its('body')
.then(body => body.json())
.then(body => {
let units = jp.query(body, "$..[?(#.type=='PROJECT')].name");
})
or
cy.request(*some request*)
.then(response => response.json())
.then(jsonObj => {
let units = jp.query(jsonObj, "$..[?(#.type=='PROJECT')].name");
})

How to access first element in array of nested objects?

I have the following JSON data like so:
[{
"target": {
"source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0",
"selector": {
"conformsTo": "http://www.w3.org/TR/media-frags/",
"value": "xywh=pixel:582.6087036132812,114.49275207519531,98.55072021484375,189.85508728027344",
"type": "FragmentSelector"
}
},
"id": "#423647a0-bd23-11ea-8727-73bc60edcd34",
"body": [{
"created": "2020-07-03T11:49:32.058Z",
"purpose": "commenting",
"type": "TextualBody",
"creator": {
"name": "testme",
"id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
},
"value": "don't move me"
}, {
"creator": {
"name": "testme",
"id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
},
"value": "move",
"type": "TextualBody",
"purpose": "tagging",
"created": "2020-07-03T11:49:30.850Z"
}],
"#context": "http://www.w3.org/ns/anno.jsonld",
"type": "Annotation",
"photoDocId": "92wNwz2aaqy7CWf3mGo1"
}, {
"#context": "http://www.w3.org/ns/anno.jsonld",
"body": [{
"type": "TextualBody",
"purpose": "commenting",
"created": "2020-07-03T10:57:40.590Z",
"value": "anyone ever climb this mountain top?",
"creator": {
"id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92",
"name": "doss"
}
}, {
"created": "2020-07-03T10:57:39.351Z",
"value": "ridge",
"type": "TextualBody",
"creator": {
"name": "doss",
"id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
},
"purpose": "tagging"
}, {
"value": "i did in 2005",
"purpose": "commenting",
"type": "TextualBody",
"creator": {
"id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2",
"name": "testme"
},
"created": "2020-07-03T10:59:45.318Z"
}, {
"type": "TextualBody",
"purpose": "tagging",
"creator": {
"name": "testme",
"id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
},
"value": "testme",
"created": "2020-07-03T10:59:43.966Z"
}, {
"value": "test",
"type": "TextualBody",
"purpose": "replying",
"creator": {
"name": "doss",
"id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
},
"created": "2020-07-03T11:39:18.860Z"
}],
"type": "Annotation",
"photoDocId": "92wNwz2aaqy7CWf3mGo1",
"id": "#03a1f0e0-bd1c-11ea-a688-e1387cc6bed2",
"target": {
"selector": {
"value": "xywh=pixel:247.82608032226562,73.91304016113281,233.33334350585938,240.57972717285156",
"type": "FragmentSelector",
"conformsTo": "http://www.w3.org/TR/media-frags/"
},
"source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0"
}
}, {
"body": [{
"value": "test",
"created": "2020-07-05T11:29:14.742Z",
"purpose": "commenting",
"creator": {
"name": "doss",
"id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
},
"type": "TextualBody"
}, {
"creator": {
"name": "doss",
"id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
},
"created": "2020-07-05T11:29:13.584Z",
"value": "test",
"purpose": "tagging",
"type": "TextualBody"
}],
"type": "Annotation",
"target": {
"selector": {
"conformsTo": "http://www.w3.org/TR/media-frags/",
"value": "xywh=pixel:395.65216064453125,413.0434875488281,142.02899169921875,131.88406372070312",
"type": "FragmentSelector"
},
"source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0"
},
"photoDocId": "92wNwz2aaqy7CWf3mGo1",
"id": "#c1761960-beb2-11ea-888f-c3ab54e1f3a9",
"#context": "http://www.w3.org/ns/anno.jsonld"
}]
This data is annotation data for an image.
What I am trying to do is loop through each object's body and only check the first element's (ie, body[0].creator.id) creator field. I want to check the id value in that creator field. If the id is the original author's id (lets use the id 0qbvzjI3llhyIrKVO6PZxcZUSiI2 for this example), then return console.log('original author').
I need help with accessing the above element. Any tips?
Side note: The reason for the above workflow is because I need to prevent another user from editing the author's original annotation. The original author will always be the first element in each body.
You could try this
const data = [
{
target: {
source:
'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0',
selector: {
conformsTo: 'http://www.w3.org/TR/media-frags/',
value:
'xywh=pixel:582.6087036132812,114.49275207519531,98.55072021484375,189.85508728027344',
type: 'FragmentSelector'
}
},
id: '#423647a0-bd23-11ea-8727-73bc60edcd34',
body: [
{
created: '2020-07-03T11:49:32.058Z',
purpose: 'commenting',
type: 'TextualBody',
creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
value: "don't move me"
},
{
creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
value: 'move',
type: 'TextualBody',
purpose: 'tagging',
created: '2020-07-03T11:49:30.850Z'
}
],
'#context': 'http://www.w3.org/ns/anno.jsonld',
type: 'Annotation',
photoDocId: '92wNwz2aaqy7CWf3mGo1'
},
{
'#context': 'http://www.w3.org/ns/anno.jsonld',
body: [
{
type: 'TextualBody',
purpose: 'commenting',
created: '2020-07-03T10:57:40.590Z',
value: 'anyone ever climb this mountain top?',
creator: { id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92', name: 'doss' }
},
{
created: '2020-07-03T10:57:39.351Z',
value: 'ridge',
type: 'TextualBody',
creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
purpose: 'tagging'
},
{
value: 'i did in 2005',
purpose: 'commenting',
type: 'TextualBody',
creator: { id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2', name: 'testme' },
created: '2020-07-03T10:59:45.318Z'
},
{
type: 'TextualBody',
purpose: 'tagging',
creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
value: 'testme',
created: '2020-07-03T10:59:43.966Z'
},
{
value: 'test',
type: 'TextualBody',
purpose: 'replying',
creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
created: '2020-07-03T11:39:18.860Z'
}
],
type: 'Annotation',
photoDocId: '92wNwz2aaqy7CWf3mGo1',
id: '#03a1f0e0-bd1c-11ea-a688-e1387cc6bed2',
target: {
selector: {
value:
'xywh=pixel:247.82608032226562,73.91304016113281,233.33334350585938,240.57972717285156',
type: 'FragmentSelector',
conformsTo: 'http://www.w3.org/TR/media-frags/'
},
source:
'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0'
}
},
{
body: [
{
value: 'test',
created: '2020-07-05T11:29:14.742Z',
purpose: 'commenting',
creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
type: 'TextualBody'
},
{
creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
created: '2020-07-05T11:29:13.584Z',
value: 'test',
purpose: 'tagging',
type: 'TextualBody'
}
],
type: 'Annotation',
target: {
selector: {
conformsTo: 'http://www.w3.org/TR/media-frags/',
value:
'xywh=pixel:395.65216064453125,413.0434875488281,142.02899169921875,131.88406372070312',
type: 'FragmentSelector'
},
source:
'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0'
},
photoDocId: '92wNwz2aaqy7CWf3mGo1',
id: '#c1761960-beb2-11ea-888f-c3ab54e1f3a9',
'#context': 'http://www.w3.org/ns/anno.jsonld'
}
]
data.forEach(d => {
if (d.body[0].creator.id === '0qbvzjI3llhyIrKVO6PZxcZUSiI2') {
console.log('original author')
}
})

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

Categories

Resources