how to write multiple file using recursive function - javascript

i wanna write file in one call but i cant looping for creating path.
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
to many statment if i using condition to create new file
asyncForEach(items, async (element) => {
if(element.hasOwnProperty('item')){
const path = 'tests/'+element.name;
console.log(path);
fs.mkdirSync(path, { recursive: true })
// await waitFor(50)
asyncForEach(element.item, async (second) => {
const second_path = path
if(second.hasOwnProperty('item') == false){
// console.log(second.name)
write(second, path, contents)
this is the input JSON
{
"info": {
"_postman_id": "fcf35761-60a4-44e8-adf9-cb871a823e38",
"name": "Reqres In",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Users",
"item": [
{
"name": "LIST USERS",
"event": [
{
"listen": "test",
"script": {
"id": "17155c09-d1cd-467c-8d45-94d2c0f7d728",
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{URL}}/api/users",
"host": [
"{{URL}}"
],
"path": [
"api",
"users"
]
}
},
"response": []
},
{
"name": "SINGLE USER",
"event": [
{
"listen": "test",
"script": {
"id": "3b1d6983-204f-4da7-a901-4ee4bfd6b69d",
"exec": [
"pm.test(\"Status code is 201\", function () {",
" pm.response.to.have.status(200);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{URL}}/api/users/2",
"host": [
"{{URL}}"
],
"path": [
"api",
"users",
"2"
]
}
},
"response": []
},
{
"name": "SINGLE USER NOT FOUND",
"event": [
{
"listen": "test",
"script": {
"id": "9e63a01c-a60a-4ac8-ac25-2e2d99614781",
"exec": [
"pm.test(\"Status code is 404\", function () {",
" pm.response.to.have.status(404);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "{{URL}}/api/users/23",
"host": [
"{{URL}}"
],
"path": [
"api",
"users",
"23"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
},
{
"name": "Create",
"item": [
{
"name": "CREATE",
"event": [
{
"listen": "test",
"script": {
"id": "35b3b52e-3dfa-4503-8437-1c826a60f283",
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"name\": \"john doe\",\n \"job\": \"leader\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/users",
"host": [
"{{URL}}"
],
"path": [
"api",
"users"
]
}
},
"response": []
},
{
"name": "UPDATE - PUT",
"event": [
{
"listen": "test",
"script": {
"id": "34b75157-7d92-486b-80fc-f14ffbde2870",
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "PUT",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"name\": \"morpheus\",\n \"job\": \"zion resident\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/users/2",
"host": [
"{{URL}}"
],
"path": [
"api",
"users",
"2"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
},
{
"name": "Registrasi",
"item": [
{
"name": "Registrasi Success",
"event": [
{
"listen": "test",
"script": {
"id": "e1ca180d-406b-4577-bdff-bfa90409e3b0",
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"{{email}}\",\n \"password\": \"pistol\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/register",
"host": [
"{{URL}}"
],
"path": [
"api",
"register"
]
}
},
"response": []
},
{
"name": "Registrasi Failed",
"event": [
{
"listen": "test",
"script": {
"id": "83cad3df-b243-4822-a359-5881a8573319",
"exec": [
"pm.test(\"Status code is 400\", function () {",
" pm.response.to.have.status(400);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"sydney#fife\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/register",
"host": [
"{{URL}}"
],
"path": [
"api",
"register"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
},
{
"name": "Login",
"item": [
{
"name": "LOGIN - SUCCESSFUL",
"event": [
{
"listen": "test",
"script": {
"id": "510fc7b5-3a1f-41c4-932f-c7865c693aa6",
"exec": [
"pm.test(\"Status code is 200\", function () {",
" pm.response.to.have.status(200);",
"});",
"",
"var jsonData = JSON.parse(responseBody);",
"pm.environment.set(\"token\", jsonData.token);"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"eve.holt#reqres.in\",\n \"password\": \"cityslicka\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/login",
"host": [
"{{URL}}"
],
"path": [
"api",
"login"
]
}
},
"response": []
},
{
"name": "LOGIN - UNSUCCESSFUL",
"event": [
{
"listen": "test",
"script": {
"id": "4bb57fea-29ab-4e61-a21c-deb0b2a9cd9a",
"exec": [
"pm.test(\"Status code is 400\", function () {",
" pm.response.to.have.status(400);",
"});"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\n \"email\": \"peter#klaven\"\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "{{URL}}/api/login",
"host": [
"{{URL}}"
],
"path": [
"api",
"login"
]
}
},
"response": []
}
],
"protocolProfileBehavior": {}
}
],
"protocolProfileBehavior": {}
}

i guess this is what you wan't, to recursively add path when meet dir, write to file when it's leaf node, while not aware of your logic detail, this is a demo code just to clarify how to transform your code to recursive model.
please check ,any more question leave your comment:
async doFileWriteJob(array, path) {
for (let index = 0; index < array.length; index++) {
element = array[index]
if(element.hasOwnProperty('item')){
if(!path) {
path = 'tests'
} else {
path = path + '/' + element.name;
}
console.log(path);
if(element.item && element.item.length > 0) {
fs.mkdirSync(path, { recursive: true })
// await waitFor(50)
doFileWriteJob(element.item, path)
} else {
if(element.hasOwnProperty('item') == false){
// console.log(element.name)
write(element, path, element.contents)
}
}
}
}
})
doFileWriteJob(array, '');

Related

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);

How to update a value in a complex fhirBundle JSON?

Given a bewildering fhir document like https://raw.githubusercontent.com/Notarise-gov-sg/api-notarise-healthcerts/master/test/fixtures/v2/pdt_art_with_nric_unwrapped.json
I need to update the part the JSON from { "id": "NRIC-FIN", "value": "S9098989Z" } to { "id": "NRIC-FIN", "value": "foobar" } and then emit the whole JSON again with that change.
I just about know how to access the value.
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value;
console.log(nric);
Though I am puzzled how to update this value since it's so difficult to access. Am I missing a trick? I don't want to use regex btw!
You seem to be very close - why not just set .value using the syntax you already have...?
const fs = require("fs");
let rawdata = fs.readFileSync("pdt_art_with_nric_unwrapped.json");
let art = JSON.parse(rawdata);
let nric = art.fhirBundle.entry
.flatMap((entry) => entry.resource)
.find((entry) => entry.resourceType === "Patient")
.identifier.find((entry) => entry.id === "NRIC-FIN").value = 'foobar';
console.dir(art.fhirBundle.entry)
... results in:
[
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{
"system": "urn:iso:std:iso:3166",
"code": "SG"
}
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{
"id": "NRIC-FIN",
"value": "foobar"
}
],
"name": [
{
"text": "Tan Chen Chen"
}
],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:7729970e-ab26-469f-b3e5-36a42ec24146",
"resource": {
"resourceType": "Observation",
"specimen": {
"type": "Specimen",
"reference": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae"
},
"performer": [
{
"type": "Practitioner",
"reference": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b"
},
{
"id": "LHP",
"type": "Organization",
"reference": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1"
}
],
"identifier": [
{
"id": "ACSN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "ACSN",
"display": "Accession ID"
}
]
},
"value": "123456789"
}
],
"category": [
{
"coding": [
{
"system": "http://snomed.info/sct",
"code": "840539006",
"display": "COVID-19"
}
]
}
],
"code": {
"coding": [
{
"system": "http://loinc.org",
"code": "97097-0",
"display": "SARS-CoV-2 (COVID-19) Ag [Presence] in Upper respiratory specimen by Rapid immunoassay"
}
]
},
"valueCodeableConcept": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "260385009",
"display": "Negative"
}
]
},
"effectiveDateTime": "2020-09-28T06:15:00Z",
"status": "final"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": {
"collectedDateTime": "2020-09-27T06:15:00Z"
}
}
},
{
"fullUrl": "urn:uuid:3dbff0de-d4a4-4e1d-98bf-af7428b8a04b",
"resource": {
"resourceType": "Practitioner",
"name": [
{
"text": "Dr Michael Lim"
}
],
"qualification": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MCR",
"display": "Practitioner Medicare number"
}
]
},
"identifier": [
{
"id": "MCR",
"value": "123456"
}
],
"issuer": {
"type": "Organization",
"reference": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e"
}
}
]
}
},
{
"fullUrl": "urn:uuid:bc7065ee-42aa-473a-a614-afd8a7b30b1e",
"resource": {
"resourceType": "Organization",
"name": "Ministry of Health (MOH)",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "govt",
"display": "Government"
}
]
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.moh.gov.sg"
},
{
"system": "phone",
"value": "+6563259220"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "Ministry of Health, 16 College Road, College of Medicine Building, Singapore 169854"
}
}
]
}
},
{
"fullUrl": "urn:uuid:fa2328af-4882-4eaa-8c28-66dab46950f1",
"resource": {
"resourceType": "Organization",
"name": "MacRitchie Medical Clinic",
"type": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/organization-type",
"code": "prov",
"display": "Healthcare Provider"
}
],
"text": "Licensed Healthcare Provider"
}
],
"contact": [
{
"telecom": [
{
"system": "url",
"value": "https://www.macritchieclinic.com.sg"
},
{
"system": "phone",
"value": "+6561234567"
}
],
"address": {
"type": "physical",
"use": "work",
"text": "MacRitchie Hospital, Thomson Road, Singapore 123000"
}
}
]
}
},
{
"fullUrl": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777",
"resource": {
"resourceType": "Device",
"type": {
"coding": [
{
"system": "https://covid-19-diagnostics.jrc.ec.europa.eu/devices",
"code": "1232",
"display": "Abbott Rapid Diagnostics, Panbio COVID-19 Ag Rapid Test"
}
]
}
}
}
]
... clearly showing foobar set as you seem to desire. (Feel free to test with this Repl.it).
To "emit the full JSON" again you would just re-stringify it:
let fullJSON = JSON.stringify(art);
Instead of traversing the object manually you can use library like Jsonpath:
function replace() {
data = JSON.parse(data);
jsonpath.apply(data,
'$.fhirBundle.entry[?(#.resource.resourceType == "Patient")].resource.identifier[?(#.id == "NRIC-FIN")].value',
function(value) {
document.body.innerHTML += `value=${value}<br>`;
return 'foobar';
});
document.body.innerHTML += `updated JSON:<br> <pre>${JSON.stringify(data, undefined, 2)}</pre`;
}
let data =
`{
"id": "340139b0-8e92-4ed6-a589-d54730f52963",
"version": "pdt-healthcert-v2.0",
"type": "ART",
"validFrom": "2021-08-24T04:22:36.062Z",
"fhirVersion": "4.0.1",
"fhirBundle": {
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"fullUrl": "urn:uuid:ba7b7c8d-c509-4d9d-be4e-f99b6de29e23",
"resource": {
"resourceType": "Patient",
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-nationality",
"extension": [
{
"url": "code",
"valueCodeableConcept": {
"text": "Patient Nationality",
"coding": [
{ "system": "urn:iso:std:iso:3166", "code": "SG" }
]
}
}
]
}
],
"identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
},
{
"fullUrl": "urn:uuid:0275bfaf-48fb-44e0-80cd-9c504f80e6ae",
"resource": {
"resourceType": "Specimen",
"subject": {
"type": "Device",
"reference": "urn:uuid:9103a5c8-5957-40f5-85a1-e6633e890777"
},
"type": {
"coding": [
{
"system": "http://snomed.info/sct",
"code": "697989009",
"display": "Anterior nares swab"
}
]
},
"collection": { "collectedDateTime": "2020-09-27T06:15:00Z" }
}
}
]
},
"issuers": [
{
"id": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830",
"revocation": { "type": "NONE" },
"name": "SAMPLE CLINIC",
"identityProof": {
"type": "DNS-DID",
"location": "donotverify.testing.verify.gov.sg",
"key": "did:ethr:0xE39479928Cc4EfFE50774488780B9f616bd4B830#controller"
}
}
],
"$template": {
"name": "HEALTH_CERT",
"type": "EMBEDDED_RENDERER",
"url": "https://healthcert.renderer.moh.gov.sg/"
}
}`
replace();
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.1.1/jsonpath.min.js"></script>
If you are flat out replacing values without any other logic, and in case if you decide to use RegEx, then you can use String.replace().
let data =
`{ "identifier": [
{
"id": "PPN",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "PPN",
"display": "Passport Number"
}
]
},
"value": "E7831177G"
},
{ "id": "NRIC-FIN", "value": "S9098989Z" }
],
"name": [{ "text": "Tan Chen Chen" }],
"gender": "female",
"birthDate": "1990-01-15"
}
}`
let targetId = 'NRIC-FIN';
let find = new RegExp(`(?<=${targetId}.*value":\\s*").*?(?=")`, 'ig');
data = data.replace(find, 'foobar');;
document.write(`<pre>${data}</pre>`);
Note: In the regular expression, I have used i flag for case insensitive search. Used g flag to replace all occurrences of the id. If the id is unique and there is going to be only one occurrence in entire .json file then don't use g flag.

Get a value from Nested JSON

I am completely new to Node.js. I have to read specific value from a API responded Nested JSON. I have tried to figure out but getting Undefined instead of the value. Whenever I am trying to read the base object I am getting the responded value but whenever I am trying to read the object under array then I am getting Undefined value.
Code Snippet:
var https = require('https');
var optionget = {
host: 'api-dev.dataoverflow.com',
port: 443,
path: '/test1/test2/',
method: 'GET',
HEADERS: {
'Authorization': 'Basic grege==',
'X-PruAppID : '
PlainCardPortal '
}
};
console.info(optionsget)
var reqGet = htttps.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
process.stdout.write(jsonobj);
var Value = jsonobj.items.item.topping.type;
console.log(Value)
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
var optionsgetmsg = {
host: 'api-dev.dataoverflow.com',
port: 443,
method: 'GET'
};
console.info(optionsgetmsg);
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf-8')
res.on('data', function(data) {
process.stdout.write(data);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
Nested JSON Snippet:
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
...
]
}
}
I want to read type : Glazed from this JSON only but I am getting Undefined.
You have to iterate over the values in an array. You cannot access them using . notation. Use map to iterate over the array and get they types in the topping array
var jsonobj = {
"items": {
"item": [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
},
{
"id": "5006",
"type": "Chocolate with Sprinkles"
},
{
"id": "5003",
"type": "Chocolate"
},
{
"id": "5004",
"type": "Maple"
}
]
}
]
}
}
var Value = jsonobj.items.item.map(e=>e.topping)[0].map(x=>x.type);
console.log(...Value)

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)

Using the AWS API Gateway SDK for Javascript

I'm trying to use the AmzaonWebService Api Gateway SDK for Javascript without success.
I've all the time the console error message : "Access Control Allow origin missing"
This is how I do:
dataFactory.setConfig = function() {
var config = {
accessKey: 'xxxxxxxxxxxxxx', // AWS Access KEY ID
secretKey: 'xxxxxxxxxx/xxxxxxxxxx/xxxxxxxx', // AWS Secret Key ID
sessionToken: dataFactory.getCognitoCredentials().idToken.jwtToken,
region: 'eu-west-1',
apiKey: undefined,
defaultContentType: 'application/json',
defaultAcceptType: 'application/json'
};
return config
}
var apigClient = apigClientFactory.newClient(dataFactory.setConfig());
dataFactory.getAll = function() {
var params = {
headers: {
"Access-Control-Allow-Origin": "*"
}
}
apigClient.allGet(params).then(function(res) {
console.log(res);
return res
}).catch(function(res) {
console.log(res);
})
};
This is how I'm getting the credentials:
dataFactory.getCognitoCredentials = function() {
var res;
var poolData = {
UserPoolId: 'eu-west-1_xxxxxxxx',
ClientId: 'xxxxxxxxxxxxxxx'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
cognitoUser.getSession(function(err, session) {
if (err) {
alert(err);
return;
}
res = session
});
}
return res;
}
Does someone know what I'm doing wrong ?
You need to setup the CORS headers on API Gateway's response and an OPTION method as a pre-flight method. I have an example swagger file which has CORS setup. You might want to take a look.
{
"swagger": "2.0",
"info": {
"description": "Your first API with Amazon API Gateway. This is a sample API that integrates via HTTP with our demo Pet Store endpoints",
"title": "PetStore"
},
"schemes": [
"https"
],
"paths": {
"/": {
"get": {
"tags": [
"pets"
],
"description": "PetStore HTML web page containing API usage information",
"consumes": [
"application/json"
],
"produces": [
"text/html"
],
"responses": {
"200": {
"description": "Successful operation",
"headers": {
"Content-Type": {
"type": "string",
"description": "Media type of request"
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Content-Type": "'text/html'"
},
"responseTemplates": {
"text/html": "<html>\n <head>\n <style>\n body {\n color: #333;\n font-family: Sans-serif;\n max-width: 800px;\n margin: auto;\n }\n </style>\n </head>\n <body>\n <h1>Welcome to your Pet Store API</h1>\n <p>\n You have succesfully deployed your first API. You are seeing this HTML page because the <code>GET</code> method to the root resource of your API returns this content as a Mock integration.\n </p>\n <p>\n The Pet Store API contains the <code>/pets</code> and <code>/pets/{petId}</code> resources. By making a <code>GET</code> request to <code>/pets</code> you can retrieve a list of Pets in your API. If you are looking for a specific pet, for example the pet with ID 1, you can make a <code>GET</code> request to <code>/pets/1</code>.\n </p>\n <p>\n You can use a REST client such as Postman to test the <code>POST</code> methods in your API to create a new pet. Use the sample body below to send the <code>POST</code> request:\n </p>\n <pre>\n{\n \"type\" : \"cat\",\n \"price\" : 123.11\n}\n </pre>\n </body>\n</html>"
}
}
},
"passthroughBehavior": "when_no_match",
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"type": "mock"
}
}
},
"/pets": {
"get": {
"tags": [
"pets"
],
"summary": "List all pets",
"produces": [
"application/json"
],
"parameters": [
{
"name": "type",
"in": "query",
"description": "The type of pet to retrieve",
"required": false,
"type": "string"
},
{
"name": "page",
"in": "query",
"description": "Page number of results to return.",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/Pets"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string",
"description": "URI that may access the resource"
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
}
},
"requestParameters": {
"integration.request.querystring.page": "method.request.querystring.page",
"integration.request.querystring.type": "method.request.querystring.type"
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http"
}
},
"post": {
"tags": [
"pets"
],
"operationId": "CreatePet",
"summary": "Create a pet",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "NewPet",
"required": true,
"schema": {
"$ref": "#/definitions/NewPet"
}
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/NewPetResponse"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string",
"description": "URI that may access the resource"
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
}
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"type": "http"
}
},
"options": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string",
"description": "URI that may access the resource"
},
"Access-Control-Allow-Methods": {
"type": "string",
"description": "Method or methods allowed when accessing the resource"
},
"Access-Control-Allow-Headers": {
"type": "string",
"description": "Used in response to a preflight request to indicate which HTTP headers can be used when making the request."
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Methods": "'POST,GET,OPTIONS'",
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
}
},
"passthroughBehavior": "when_no_match",
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"type": "mock"
}
}
},
"/pets/{petId}": {
"get": {
"tags": [
"pets"
],
"summary": "Info for a specific pet",
"operationId": "GetPet",
"produces": [
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "The id of the pet to retrieve",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/Pet"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string",
"description": "URI that may access the resource"
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
}
},
"requestParameters": {
"integration.request.path.petId": "method.request.path.petId"
},
"uri": "http://petstore-demo-endpoint.execute-api.com/petstore/pets/{petId}",
"passthroughBehavior": "when_no_match",
"httpMethod": "GET",
"type": "http"
}
},
"options": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "The id of the pet to retrieve",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "Successful operation",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string",
"description": "URI that may access the resource"
},
"Access-Control-Allow-Methods": {
"type": "string",
"description": "Method or methods allowed when accessing the resource"
},
"Access-Control-Allow-Headers": {
"type": "string",
"description": "Used in response to a preflight request to indicate which HTTP headers can be used when making the request."
}
}
}
},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Methods": "'GET,OPTIONS'",
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
"method.response.header.Access-Control-Allow-Origin": "'*'"
}
}
},
"passthroughBehavior": "when_no_match",
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"type": "mock"
}
}
}
},
"definitions": {
"Pets": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
},
"Empty": {
"type": "object"
},
"NewPetResponse": {
"type": "object",
"properties": {
"pet": {
"$ref": "#/definitions/Pet"
},
"message": {
"type": "string"
}
}
},
"Pet": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"type": {
"type": "string"
},
"price": {
"type": "number"
}
}
},
"NewPet": {
"type": "object",
"properties": {
"type": {
"$ref": "#/definitions/PetType"
},
"price": {
"type": "number"
}
}
},
"PetType": {
"type": "string",
"enum": [
"dog",
"cat",
"fish",
"bird",
"gecko"
]
}
},
"x-amazon-apigateway-documentation": {
"version": "v2.1",
"createdDate": "2016-11-17T07:03:59Z",
"documentationParts": [
{
"location": {
"type": "API"
},
"properties": {
"info": {
"description": "Your first API with Amazon API Gateway. This is a sample API that integrates via HTTP with our demo Pet Store endpoints"
}
}
},
{
"location": {
"type": "METHOD",
"method": "GET"
},
"properties": {
"tags": [
"pets"
],
"description": "PetStore HTML web page containing API usage information"
}
},
{
"location": {
"type": "METHOD",
"path": "/pets/{petId}",
"method": "GET"
},
"properties": {
"tags": [
"pets"
],
"summary": "Info for a specific pet"
}
},
{
"location": {
"type": "METHOD",
"path": "/pets",
"method": "GET"
},
"properties": {
"tags": [
"pets"
],
"summary": "List all pets"
}
},
{
"location": {
"type": "METHOD",
"path": "/pets",
"method": "POST"
},
"properties": {
"tags": [
"pets"
],
"summary": "Create a pet"
}
},
{
"location": {
"type": "PATH_PARAMETER",
"path": "/pets/{petId}",
"method": "*",
"name": "petId"
},
"properties": {
"description": "The id of the pet to retrieve"
}
},
{
"location": {
"type": "QUERY_PARAMETER",
"path": "/pets",
"method": "GET",
"name": "page"
},
"properties": {
"description": "Page number of results to return."
}
},
{
"location": {
"type": "QUERY_PARAMETER",
"path": "/pets",
"method": "GET",
"name": "type"
},
"properties": {
"description": "The type of pet to retrieve"
}
},
{
"location": {
"type": "REQUEST_BODY",
"path": "/pets",
"method": "POST"
},
"properties": {
"description": "Pet object that needs to be added to the store"
}
},
{
"location": {
"type": "RESPONSE",
"method": "*",
"statusCode": "200"
},
"properties": {
"description": "Successful operation"
}
},
{
"location": {
"type": "RESPONSE_HEADER",
"method": "OPTIONS",
"statusCode": "200",
"name": "Access-Control-Allow-Headers"
},
"properties": {
"description": "Used in response to a preflight request to indicate which HTTP headers can be used when making the request."
}
},
{
"location": {
"type": "RESPONSE_HEADER",
"method": "OPTIONS",
"statusCode": "200",
"name": "Access-Control-Allow-Methods"
},
"properties": {
"description": "Method or methods allowed when accessing the resource"
}
},
{
"location": {
"type": "RESPONSE_HEADER",
"method": "*",
"statusCode": "200",
"name": "Access-Control-Allow-Origin"
},
"properties": {
"description": "URI that may access the resource"
}
},
{
"location": {
"type": "RESPONSE_HEADER",
"method": "GET",
"statusCode": "200",
"name": "Content-Type"
},
"properties": {
"description": "Media type of request"
}
}
]
}
}

Categories

Resources