Postman- Retrieve specific key values from JSON object - javascript

`I got this response from the api call and I need to extract specific values from the response. Also, I want to use it as a pre request script in another api call.
How can I extract values of the ids from the Json object?
2)Is it possible to extract particular value of the id key where key from equals "rahul.sharma#gmail.com"?
{
"content": [
{
"id": "e7ab9f7d-c9f4-47e3-8d53-6febcfb914",
"from": "raulsdirect#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2c2965dc5ca34#mailslurp.mx"
],
"subject": "id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dc34221",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T15:43:02.357Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\">id 23543253534<div>sid 34645656452342342343424</div></div>\r\n",
"teamAccess": true,
"bodyMD5Hash": "F2956A8791EB5E6F6F6E259C112BB13B"
},
{
"id": "8d547247-32d2-4553-b1fe-33b4ca00221d2",
"from": "rahul.sharma#adtraction.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-243d965dc5ba8#mailslurp.mx"
],
"subject": "Re: saas",
"inboxId": "af09331a-d681-48c4-9075-2c263f2dc5ba8",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T22:20:23.301Z",
"read": true,
"bodyExcerpt": "<div dir=\"auto\"><div dir=\"auto\"></div><p style=\"font-size:12.8px\">sid 325sd-df435-3fdgvd435-gdfv43</",
"teamAccess": true,
"bodyMD5Hash": "948B78E301880858EB66ABDE6698450B"
},
{
"id": "446760be-e261-441a-bffe-fa31aa935239",
"from": "rahul.sharma#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"10ea0b7b-b5eb-4c0f-908d-39437f2214a71#mailslurp.com"
],
"subject": "Complete your registration",
"inboxId": "10ea0b7b-b5eb-4c0f-908d-394354324a71",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T07:41:41.685Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "3A7619478AB69B1F63C99B9716896B1B"
},
{
"id": "79a2c183-5b72-4bc1-98aa-63bf5d52c2e6",
"from": "raulsdirect#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2532165dc5ba8#mailslurp.mx"
],
"subject": "Re: id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dbdf5328",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T19:20:44.655Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "1ED8849F70CBCBBA6CF3CFEA0ACA66C4"
}
],
"pageable": {
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 20,
"paged": true,
"unpaged": false
},
"last": true,
"totalElements": 4,
"totalPages": 1,
"size": 20,
"number": 0,
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"first": true,
"numberOfElements": 4,
"empty": false
}
`

To parse json, in JS there is a native way to do it.
JSON.parse()
Example of usage:
const data = JSON.parse(yourJsonObject);
then:
console.log(data.content) in your case will return:
[
{
"id": "e7ab9f7d-c9f4-47e3-8d53-6febcfb914",
"from": "raulsdirect#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2c2965dc5ca34#mailslurp.mx"
],
"subject": "id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dc34221",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T15:43:02.357Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\">id 23543253534<div>sid 34645656452342342343424</div></div>\r\n",
"teamAccess": true,
"bodyMD5Hash": "F2956A8791EB5E6F6F6E259C112BB13B"
}, ...
]

as you want to find id of the content with from that equals to "rahul.sharma#gmail.com" and content is an array of object so, you can use filter method of array like this.
const result=response.content.filter(value=>value.from=="rahul.sharma#gmail.com");
result variable will contain the whole object which match with your email so if you want only id then you can get it by using another map property.
const ids=result.map(item=>item.id);

You can access to JSON object directly but if you want to convert to JS Object use JSON.parse()
//You can access to JSON object, but if you prefer to get JS Object do this: JSON.parse(objJSON)
const objJSON = {
"content": [
{
"id": "e7ab9f7d-c9f4-47e3-8d53-6febcfb914",
"from": "raulsdirect#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2c2965dc5ca34#mailslurp.mx"
],
"subject": "id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dc34221",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T15:43:02.357Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\">id 23543253534<div>sid 34645656452342342343424</div></div>\r\n",
"teamAccess": true,
"bodyMD5Hash": "F2956A8791EB5E6F6F6E259C112BB13B"
},
{
"id": "8d547247-32d2-4553-b1fe-33b4ca00221d2",
"from": "rahul.sharma#adtraction.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-243d965dc5ba8#mailslurp.mx"
],
"subject": "Re: saas",
"inboxId": "af09331a-d681-48c4-9075-2c263f2dc5ba8",
"bcc": [],
"cc": [],
"createdAt": "2022-11-01T22:20:23.301Z",
"read": true,
"bodyExcerpt": "<div dir=\"auto\"><div dir=\"auto\"></div><p style=\"font-size:12.8px\">sid 325sd-df435-3fdgvd435-gdfv43</",
"teamAccess": true,
"bodyMD5Hash": "948B78E301880858EB66ABDE6698450B"
},
{
"id": "446760be-e261-441a-bffe-fa31aa935239",
"from": "rahul.sharma#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"10ea0b7b-b5eb-4c0f-908d-39437f2214a71#mailslurp.com"
],
"subject": "Complete your registration",
"inboxId": "10ea0b7b-b5eb-4c0f-908d-394354324a71",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T07:41:41.685Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "3A7619478AB69B1F63C99B9716896B1B"
},
{
"id": "79a2c183-5b72-4bc1-98aa-63bf5d52c2e6",
"from": "raulsdirect#gmail.com",
"domainId": null,
"attachments": [],
"to": [
"af09331a-d681-48c4-9075-2532165dc5ba8#mailslurp.mx"
],
"subject": "Re: id and sid",
"inboxId": "af09331a-d681-48c4-9075-2c2965dbdf5328",
"bcc": [],
"cc": [],
"createdAt": "2022-11-02T19:20:44.655Z",
"read": true,
"bodyExcerpt": "<div dir=\"ltr\"><span style=\"color:unset;font:unset;font-feature-settings:unset;font-kerning:unset;fo",
"teamAccess": true,
"bodyMD5Hash": "1ED8849F70CBCBBA6CF3CFEA0ACA66C4"
}
],
"pageable": {
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"offset": 0,
"pageNumber": 0,
"pageSize": 20,
"paged": true,
"unpaged": false
},
"last": true,
"totalElements": 4,
"totalPages": 1,
"size": 20,
"number": 0,
"sort": {
"empty": false,
"sorted": true,
"unsorted": false
},
"first": true,
"numberOfElements": 4,
"empty": false
}
//Array of IDs of each content object
const arrayIDs = [];
objJSON.content.forEach( c => {
arrayIDs.push( c.id );
} )
//You can get the object filtering by the attribute you need
const rahulSharma = objJSON.content.find( c => {
return c.from == "rahul.sharma#gmail.com"
} )
//Then you can access to any attribute. In this case: id
console.log(`Sahul Sharma's ID: ${rahulSharma.id}`)
console.log('All IDs')
console.log(arrayIDs)
console.log('Info of Rahul Sharma')
console.log(rahulSharma)

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

Partition messages by date, last read in angular

I want to partition my messages by date for my chat application(Similar to the Microsoft teams app)
The message data will be like
[
{
"id": 577,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "John J"
},
"body": "test test",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T07:59:28.873+00:00"
},
{
"id": 578,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Don V"
},
"body": "ok",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T08:02:26.262+00:00"
},
{
"id": 628,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Sam GP"
},
"body": "Hola",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:27:48.038+00:00"
},
{
"id": 629,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Rawn OP"
},
"body": "ek",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:29:36.705+00:00"
},
{
"id": 630,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Paul John"
},
"body": "hi",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:30:36.695+00:00"
},
{
"id": 631,
"source": {
"userID": 56470,
"profilePictureUrl": "",
"name": "Dennise V"
},
"body": "knock knock",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:32:38.035+00:00"
},
{
"id": 632,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Shawn"
},
"body": "who's this",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:25.985+00:00"
},
{
"id": 633,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Pater B"
},
"body": "I see",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:30.783+00:00"
},
{
"id": 634,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Cera LO"
},
"body": "Will call you later",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-20T17:37:38.268+00:00"
},
{
"id": 642,
"source": {
"userID": 56469,
"profilePictureUrl": "",
"name": "Rose BH"
},
"body": "hello???????",
"readStatus": true,
"attachments": null,
"createdDateTime": "2022-09-21T05:25:56.642+00:00"
}
]
I need to arrange these data to show the messages by date like
------------------------------Sep 30-----------------------------
Messages sent/received on sep 30
------------------------------Yesterday--------------------------
Messages sent/received on yesterday
------------------------------Last read-------------------------
------------------------------Oct30-----------------------------
------------------------------Yesterday-------------------------
------------------------------Today-----------------------------
For displaying "Sep 30", "yesterday", and "Today" I've created a pipe that converts the timestamp into the month and "yesterday", "today" etc.
I already got the solution to arrange the message by date. But I have to arrange it under the "Last read" block too. Same as by dates. the flag "readStatus" is sed to check whether the message has been read or not" If it is false is should come under "Last read".
Any ideas? Any help will be appreciated.
I imagine you can has something like (if your data is in a variable "data"
dataOrder = {
readed: this.group(this.data.filter((x) => x.readStatus)),
notReaded: this.group(this.data.filter((x) => !x.readStatus)),
};
group(data: any[]) {
return data.reduce((a, b) => {
const dateTime=new Date(b.createdDateTime.substr(0,10)+"T00:00:00.00+00:00")
.getTime()
const element = a.find((x) => x.dateTime == dateTime);
if (!element) a.push({ dateTime:dateTime,data: [b] });
else element.data.push(b);
return a;
}, []);
}
See that "dataOrder" has two properties "readed" and "notReaded", each one are arrays of objects in the way
{
dateTime:a dateTime,
data:an array with the messages
}
This makes easy indicate the date using Angular date pipe, and loop over the messages
So, an .html like
<h1>Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.readed }"
></ng-container>
<h1>Not Readed</h1>
<ng-container
*ngTemplateOutlet="messagedata; context: { $implicit: dataOrder.notReaded }"
></ng-container>
<ng-template #messagedata let-data>
<div *ngFor="let readed of data">
{{ readed.dateTime | date }}
<div *ngFor="let message of readed.data">
{{ message.createdDateTime }} - {{ message.body }}
</div>
</div>
</ng-template>
I use the same template for both type of messages
A stackblitz
Update As the dataOrder it's only change at fisrt is better use a function
getDataOrdered(data:any[])
{
return {
readed: this.group(data.filter((x) => x.readStatus)),
notReaded: this.group(data.filter((x) => !x.readStatus)),
};
}
Then, we can, each time some message change its "readStatus" we can do
this.dataOrder=this.getDataOrdered(this.data)

JSON not indexing correctly

I have this JSON:
[
{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}
]
(call = the json)
Shouldn't this be returning "updates": call[0]["name"]
Via JS, it is returning undefined.
call[0] is returning as {
I've tried it on various other languages and it has been working as intended... just not in JS.
It does work:
const call = [{
"type": "GUILD_TEXT",
"deleted": false,
"guild": "898666651547996200",
"guildId": "898666651547996200",
"parentId": "903388176100495390",
"permissionOverwrites": [
"900991433576689675",
"917426278003523604",
"898666651547996200",
"898825198709641246"
],
"messages": [
"928781911982219307"
],
"threads": [],
"nsfw": false,
"id": "903388255528042566",
"name": "updates",
"rawPosition": 41,
"topic": null,
"lastMessageId": "928781911982219307",
"rateLimitPerUser": 0,
"createdTimestamp": 1635454944260
}]
console.log(call[0]["name"]) // updates
const callString = JSON.stringify(call)
console.log(JSON.parse(callString)[0]["name"]) // updates
I tried
var name= call[0].name;
and
var name= call[0]["name"];
evertything is working properly returning "updates".

how to compare Json response and UI elements with 2 arrays using for loop in cypress automation

I have requirement where i need to compare json response data with UI elements . If matching elements found need to print it on log. I need to check all the json response with for loop . Could some one please help me with the code cypress with javascript code. Just to summarise i need a code how to retrieve json data, with java script and cypress. I am pasting sample json below.
from below Json response i need to retrieve the product names and compare with UI product names.
"retail": [
{
"productId": "6046998e0fce52000138c752",
"productName": "Dealer Product 2 - Perma ",
"displayName": "some notes ",
"coverageOptions": [
{
"retailCost": 1017
}
],
"isTaxable": true,
"isCapitalized": true,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
{
"productId": "610d7f6460fcad0001f6d9a6",
"productName": "Dealer Product 7",
"displayName": "This is product seven",
"coverageOptions": [
{
"retailCost": 6000
}
],
"productTypes": "servicePlan",
"isTaxable": true,
"isCapitalized": true,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
{
"productId": "610da70960fcad0001f6d9ae",
"productName": "Dealer Product 8",
"displayName": "notes....",
"coverageOptions": [
{
"retailCost": 400
}
],
"productTypes": "other",
"isTaxable": true,
"isCapitalized": false,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
{
"productId": "610da795489262000147f384",
"productName": "Dealer Product 9",
"displayName": "notes...",
"coverageOptions": [
{
"retailCost": 1000
}
],
"productTypes": "gap",
"isTaxable": false,
"isCapitalized": true,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
{
"productId": "611d15224d24510001f731f0",
"productName": "Product Ten",
"displayName": "This is Product 10",
"coverageOptions": [
{
"retailCost": 400
}
],
"productTypes": "wearCare",
"isTaxable": true,
"isCapitalized": true,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
{
"productId": "611d2df0a3e1960001d34c8c",
"productName": "Credit Disability Test",
"displayName": "This is the test product for Credit Disability push to routeone",
"coverageOptions": [
{
"retailCost": 1000
}
],
"isTaxable": false,
"isCapitalized": false,
"preferenceOrder": "",
"isTermBased": false,
"isLessOrEqualMonths": false,
"providerId": "nontmis",
"content": {}
},
So this can done using the cy.readFile()
cy.readFile("filePath").then((obj) => {
cy.log(obj); //this prints the entire json file data
userData.jsonData = obj; //now this variable contains the data
});
//I am assuming that we are verifying "productName" with UI
cy.get("UIDataToBeVerified").each((el) => {
for (var key in userData.jsonData) {
let productName = userData.jsonData.retail[`${key}`].productName;
if (el.text() == productName) {
cy.log(el.text()); //This prints the product name on UI if it matches
}
}
});

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