Can you please help me generating HTML Table by using the JSON data with Angular ng-repeat.
Demo
JSON Data
{
"account": {
"accountId": "54545",
"premise": {
"address": {
"address1": "1800 Bishop Gate Boulevard",
"address2": "Apartment 129",
"city": "Mount Laurel",
"province": "NJ",
"postalCode": "08054",
"country": "US",
"direction": null,
"externalReference": null,
"verified": false
},
"timeZone": "US_EASTERN",
"locale": "EN",
"camera": [
{
"id": "175277.2",
"name": "camera1",
"macAddress": "00:0E:8F:5B:AB:88",
"manufacturer": "gabreal",
"model": "iCamera",
"serialNumber": "000E8F5BAB88",
"firmwareVersion": "3.0.01.07",
"hardwareVersion": null
},
{
"id": "175277.3",
"name": "camera2",
"macAddress": "D4:21:22:D9:D0:73",
"manufacturer": "gabreal",
"model": "iCamera2-C",
"serialNumber": "D42122D9D073",
"firmwareVersion": "3.0.02.39",
"hardwareVersion": null
},
{
"id": "175277.1",
"name": "camera3",
"macAddress": "00:0E:8F:95:A8:A6",
"manufacturer": "gabreal",
"model": "SerComm_Camera_8021",
"serialNumber": "000E8F95A8A6",
"firmwareVersion": "1.0.24",
"hardwareVersion": null
}
],
"thermostat": [
{
"id": "0024460000084172.10",
"name": "Thermostat1",
"type": "THERMOSTAT",
"manufacturer": "RTCOA",
"serialNumber": null,
"firmwareVersion": "0x00000587",
"hardwareVersion": "192",
"model": "CT30S"
},
{
"id": "000d6f0003ec6669.1",
"name": "Thermostat2",
"type": "THERMOSTAT",
"manufacturer": "CentraLite Systems",
"serialNumber": null,
"firmwareVersion": "0x1418468c",
"hardwareVersion": "2",
"model": "3156105"
}
],
"zone": [
{
"id": 1,
"name": "one",
"type": "DOOR",
"functionType": "ENTRY_EXIT",
"sensor": [
{
"id": 1,
"type": "DRY_CONTACT",
"sourceType": "ZIGBEE",
"serialNumber": "000d6f00030cdbcf.1",
"model": "MCT-320 SMA",
"manufacturer": "Visonic",
"firmwareVersion": "0x00040008",
"hardwareVersion": "1"
}
]
},
{
"id": 2,
"name": "Motion",
"type": "MOTION",
"functionType": "INTERIOR_FOLLOWER",
"sensor": [
{
"id": 2,
"type": "MOTION",
"sourceType": "ZIGBEE",
"serialNumber": "000d6f0004b2af93.1",
"model": "NEXT K85 SMA",
"manufacturer": "Visonic",
"firmwareVersion": "0x0004000b",
"hardwareVersion": "1"
}
]
}
],
"cpe": {
"cpeId": "9c972684b2ca",
"name": null,
"deploymentModel": "WIFI_CLIENT_PSK_2_MODE",
"serialNumber": null,
"manufacturer": "Technicolor",
"model": "TCA203",
"hardwareRev": "5",
"passPhrase": "528233",
"cellularProfileName": null,
"imeiNumber": 359942045924230,
"iccId": "89011703258034552401",
"simCardPhoneNumber": null,
"simCardAccountNumber": null,
"wifiMacAddress": "70:25:59:79:E2:EE",
"firmwareVersion": "7_3_8_050000_201611152386",
"widget": [
{
"name": "com.wsi.android.Gabreal",
"version": "1.2"
},
{
"name": "com.icontrol.apps.clock",
"version": "1.0.0.0.3"
}
],
"module": []
},
"premiseId": null
},
"source": "INTERNAL"
}
}
The table I want to generate as below
<table>
<tr>
<th>Property<br></th>
<th>camera</th>
<th>camera</th>
<th>camera</th>
<th>thermostat</th>
<th>thermostat</th>
<th>sensor</th>
<th>sensor</th>
</tr>
<tr>
<td>id</td>
<td>175277.2</td>
<td>175277.3</td>
<td>175277.1</td>
<td>0024460000084172.10</td>
<td>000d6f0003ec6669.1</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>name</td>
<td>camera1</td>
<td>camera2</td>
<td>camera3</td>
<td>Thermostat1</td>
<td>Thermostat2</td>
<td></td>
<td></td>
</tr>
<tr>
<td>macAddress</td>
<td>00:0E:8F:5B:AB:88</td>
<td>D4:21:22:D9:D0:73</td>
<td>00:0E:8F:95:A8:A6</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>manufacturer</td>
<td>gabreal</td>
<td>gabreal</td>
<td>gabreal</td>
<td>RTCOA</td>
<td>CentraLite Systems</td>
<td>Visonic</td>
<td>Visonic</td>
</tr>
</table>
Note : Aruna has answered the question, but it fails when there different type JSON Object like zone object is different from others.
This is a generic solution with the object and the properties.
Updated as per the json change on the Bounty request.
var app = angular.module('studentApp', []);
app.controller('StudentCntrl', function($scope,$http) {
//$http.get('data.json').then(function (response){
//console.log(response.data.pages);
//$scope.deviceInfo = response.data.account.premise;
//});
var responseData = {
"account": {
"accountId": "54545",
"premise": {
"address": {
"address1": "1800 Bishop Gate Boulevard",
"address2": "Apartment 129",
"city": "Mount Laurel",
"province": "NJ",
"postalCode": "08054",
"country": "US",
"direction": null,
"externalReference": null,
"verified": false
},
"timeZone": "US_EASTERN",
"locale": "EN",
"camera": [
{
"id": "175277.2",
"name": "camera1",
"macAddress": "00:0E:8F:5B:AB:88",
"manufacturer": "gabreal",
"model": "iCamera",
"serialNumber": "000E8F5BAB88",
"firmwareVersion": "3.0.01.07",
"hardwareVersion": null
},
{
"id": "175277.3",
"name": "camera2",
"macAddress": "D4:21:22:D9:D0:73",
"manufacturer": "gabreal",
"model": "iCamera2-C",
"serialNumber": "D42122D9D073",
"firmwareVersion": "3.0.02.39",
"hardwareVersion": null
},
{
"id": "175277.1",
"name": "camera3",
"macAddress": "00:0E:8F:95:A8:A6",
"manufacturer": "gabreal",
"model": "SerComm_Camera_8021",
"serialNumber": "000E8F95A8A6",
"firmwareVersion": "1.0.24",
"hardwareVersion": null
}
],
"thermostat": [
{
"id": "0024460000084172.10",
"name": "Thermostat1",
"type": "THERMOSTAT",
"manufacturer": "RTCOA",
"serialNumber": null,
"firmwareVersion": "0x00000587",
"hardwareVersion": "192",
"model": "CT30S"
},
{
"id": "000d6f0003ec6669.1",
"name": "Thermostat2",
"type": "THERMOSTAT",
"manufacturer": "CentraLite Systems",
"serialNumber": null,
"firmwareVersion": "0x1418468c",
"hardwareVersion": "2",
"model": "3156105"
}
],
"zone": [
{
"id": 1,
"name": "one",
"type": "DOOR",
"functionType": "ENTRY_EXIT",
"sensor": [
{
"id": 1,
"type": "DRY_CONTACT",
"sourceType": "ZIGBEE",
"serialNumber": "000d6f00030cdbcf.1",
"model": "MCT-320 SMA",
"manufacturer": "Visonic",
"firmwareVersion": "0x00040008",
"hardwareVersion": "1"
}
]
},
{
"id": 2,
"name": "Motion",
"type": "MOTION",
"functionType": "INTERIOR_FOLLOWER",
"sensor": [
{
"id": 2,
"type": "MOTION",
"sourceType": "ZIGBEE",
"serialNumber": "000d6f0004b2af93.1",
"model": "NEXT K85 SMA",
"manufacturer": "Visonic",
"firmwareVersion": "0x0004000b",
"hardwareVersion": "1"
}
]
}
],
"cpe": {
"cpeId": "9c972684b2ca",
"name": null,
"deploymentModel": "WIFI_CLIENT_PSK_2_MODE",
"serialNumber": null,
"manufacturer": "Technicolor",
"model": "TCA203",
"hardwareRev": "5",
"passPhrase": "528233",
"cellularProfileName": null,
"imeiNumber": 359942045924230,
"iccId": "89011703258034552401",
"simCardPhoneNumber": null,
"simCardAccountNumber": null,
"wifiMacAddress": "70:25:59:79:E2:EE",
"firmwareVersion": "7_3_8_050000_201611152386",
"widget": [
{
"name": "com.wsi.android.Gabreal",
"version": "1.2"
},
{
"name": "com.icontrol.apps.clock",
"version": "1.0.0.0.3"
}
],
"module": []
},
"premiseId": null
},
"source": "INTERNAL"
}
};
var headerProperty = $scope.headerProperty = 'deviceType';
rebuildDeviceInfo(responseData);
function rebuildDeviceInfo(data) {
var deviceInfoData = responseData.account.premise;
var deviceInfo = [], deviceProperties = [];
// Parse devices
angular.forEach(deviceInfoData, function(devices, deviceKey) {
if(angular.isArray(devices)) {
deviceInfo = deviceInfo.concat(parseDevices(devices, deviceKey));
}
});
// Parse device properties
for(var i = 0; i < deviceInfo.length; i++) {
var device = deviceInfo[i];
angular.forEach(device, function(value, deviceProperty) {
if(deviceProperties.indexOf(deviceProperty) === -1) {
deviceProperties.push(deviceProperty);
}
});
}
$scope.deviceInfo = deviceInfo;
$scope.deviceProperties = deviceProperties;
}
function parseDevices(dataArray, dataKey) {
var deviceInfo = [];
if(angular.isArray(dataArray)) {
for(var i = 0; i < dataArray.length; i++) {
var data = dataArray[i];
if(data.hasOwnProperty('manufacturer') || data.hasOwnProperty('model')) {
data[headerProperty] = dataKey;
deviceInfo.push(data);
} else {
angular.forEach(data, function(devices, deviceKey) {
if(angular.isArray(devices)) {
deviceInfo = deviceInfo.concat(parseDevices(devices, deviceKey));
}
});
}
}
}
return deviceInfo;
}
});
<!DOCTYPE html>
<html ng-app="studentApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.4.7/angular.js"></script>
</head>
<body ng-controller="StudentCntrl">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Property</th>
<th ng-repeat="device in deviceInfo track by $index">{{device[headerProperty]}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="prop in deviceProperties track by $index" ng-if="prop != headerProperty">
<td>{{prop}}</td>
<td ng-repeat="device in deviceInfo track by $index">{{device[prop]}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Related
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.
I'm trying to filter data on yandex maps.
CodePen Example
If the base station has several bands (2G, 3G and 4G), then it should be in the results if at least one of its band is in the filter.
How correct filter data on yandex maps?
I have listBoxControl with listBoxItems = ['2G', '3G', '4G']
My filter function looks like this:
function getFilterFunction(categories){
return function(obj){
let bsBands = obj.has_bands;
/* How correct filter data? */
return categories['2G'] && categories['3G'] && categories['4G'];
}
}
GeoJSON looks like this:
{
"count": 4,
"next": null,
"previous": null,
"type": "FeatureCollection",
"features": [
{
"id": 1,
"region_prefix": "97",
"cell_site_number": 1,
"description": "",
"address": "",
"commissioning": "",
"bs_id": "",
"height_asl": 0,
"bands": [
{
"name": "2G",
"frequency": "900"
},
{
"name": "2G",
"frequency": "1800"
},
{
"name": "3G",
"frequency": "2100"
},
{
"name": "4G",
"frequency": "1800"
},
{
"name": "4G TDD",
"frequency": "2600"
}
],
"status": true,
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [55.755815, 37.613]
},
"properties": {
"balloonContentHeader": "balloonContentHeader",
"balloonContentBody": "balloonContentBody",
"balloonContentFooter": "balloonContentFooter",
"clusterCaption": "clusterCaption",
"hintContent": "hintContent",
"iconCaption": "2G 3G 4G"
},
"has_bands": [
"3G",
"2G",
"4G"
]
},
{
"id": 2,
"region_prefix": "97",
"cell_site_number": 2,
"description": "",
"address": "",
"commissioning": "",
"bs_id": "",
"height_asl": 0,
"bands": [
{
"name": "2G",
"frequency": "900"
},
{
"name": "2G",
"frequency": "1800"
},
{
"name": "3G",
"frequency": "2100"
},
{
"name": "4G",
"frequency": "1800"
},
{
"name": "4G TDD",
"frequency": "2600"
}
],
"status": true,
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [55.759, 37.613]
},
"properties": {
"balloonContentHeader": "balloonContentHeader",
"balloonContentBody": "balloonContentBody",
"balloonContentFooter": "balloonContentFooter",
"clusterCaption": "clusterCaption",
"hintContent": "hintContent",
"iconCaption": "2G 3G 4G"
},
"has_bands": [
"3G",
"2G",
"4G"
]
},
{
"id": 3,
"region_prefix": "97",
"cell_site_number": 3,
"description": "",
"address": "",
"commissioning": "",
"bs_id": "",
"height_asl": 0,
"bands": [
{
"name": "3G",
"frequency": "2100"
}
],
"status": true,
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [55.7204, 37.6167]
},
"properties": {
"balloonContentHeader": "balloonContentHeader",
"balloonContentBody": "balloonContentBody",
"balloonContentFooter": "balloonContentFooter",
"clusterCaption": "clusterCaption",
"hintContent": "hintContent",
"iconCaption": "3G"
},
"has_bands": [
"3G",
]
},
{
"id": 4,
"region_prefix": "97",
"cell_site_number": 4,
"description": "",
"address": "",
"commissioning": "",
"bs_id": "",
"height_asl": 0,
"bands": [
{
"name": "4G",
"frequency": "1800"
},
{
"name": "4G TDD",
"frequency": "2600"
}
],
"status": true,
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [55.7704, 37.6119]
},
"properties": {
"balloonContentHeader": "balloonContentHeader",
"balloonContentBody": "balloonContentBody",
"balloonContentFooter": "balloonContentFooter",
"clusterCaption": "clusterCaption",
"hintContent": "hintContent",
"iconCaption": "4G"
},
"has_bands": [
"4G"
]
}]}
I solved this issue myself.
CodePen Example
function getBand(e, i, a){
let Band = this.valueOf();
return e === Band;
}
function getFilterFunction(categories){
return function(obj){
let bsBands = obj.has_bands;
let has2G = bsBands.find(getBand, '2G');
let has3G = bsBands.find(getBand, '3G');
let has4G = bsBands.find(getBand, '4G');
return (categories['2G'] && has2G) || (categories['3G'] && has3G) || (categories['4G'] && has4G);
}
}
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)
I am trying to get the JSON data into list.html as follows, but my attempts are failing. I have tried following patterns described in other similar posts, but haven't had any luck and haven't found a scenario with JSON data formatted exactly like mine. How do I get the fields like givenName, familyName, primaryTitle, phones[0].value, and photo.small to show up?
index.html:
<!doctype html>
<html lang="en" ng-app="directoryApp">
<head>
<meta charset="UTF-8">
<title>Directory</title>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular/angular-route.min.js"></script>
<script src="lib/angular/angular-animate.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-view></div>
</body>
</html>
list.html:
<ul ng-show="query">
<li ng-animate="'animate'" ng-repeat="person in people.people | filter: query | orderBy: peopleOrder:direction">
<img ng-src="images/{{person.photo.small}}" alt="Photo of {{person.name.givenName}}">
<div class="info">
<h2>{{person.name.givenName}}</h2>
<h3>{{person.primaryTitle}}, {{person.phones[0].value}}</h3>
</div>
</li>
</ul>
controllers.js:
var directoryControllers = angular.module('directoryControllers', ['ngAnimate']);
directoryControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/directoryData.json').success(function(data) {
$scope.people = data;
$scope.peopleOrder = 'familyName';
});
}]);
app.js:
var directoryApp = angular.module('directoryApp', [
'ngRoute',
'directoryControllers'
]);
directoryApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListController'
}).
otherwise({
redirectTo: '/list'
});
}]);
directoryData.json:
[
{
"uid": 15,
"name": "School of Programming",
"sortKey": 0,
"type": "Academic",
"address": {
"address1": "255 Foo St",
"address2": "Suite 310",
"city": "FooBar",
"state": "FB",
"postalCode": "90210"
},
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Fax",
"value": "555-3620"
}
],
"people": [
{
"uid": "person1",
"classification": "Faculty",
"name": {
"givenName": "Roo",
"nickname": "",
"additionalName": "",
"familyName": "Baf"
},
"primaryTitle": "Part Time Worker",
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Mobile",
"value": "555-1509"
}
],
"photo": {
"small": "/__media__/photos/foo_portrait_small.jpg",
"medium": "/__media__/photos/foo_portrait_medium.jpg",
"large": "/__media__/photos/foo_portrait_large.jpg"
}
},
{
"uid": "person2",
"classification": "Faculty",
"name": {
"givenName": "Foo",
"nickname": "",
"additionalName": "P.",
"familyName": "Bar"
},
"primaryTitle": "Blah",
"phones": [
{
"type": "Work",
"value": "555-3608"
},
{
"type": "Home",
"value": "555-4716"
}
],
"photo": {
"small": "/__media__/photos/portrait_small.jpg",
"medium": "/__media__/photos/portrait_medium.jpg",
"large": "/__media__/photos/portrait_large.jpg"
}
}
]
},
{
"uid": 16,
"name": "School of Coding",
"sortKey": 1,
"type": "Academic",
"address": {
"address1": "256 Foo St",
"address2": "Suite 311",
"city": "FooBar",
"state": "FB",
"postalCode": "90210"
},
"phones": [
{
"type": "Work",
"value": "555-1616"
},
{
"type": "Fax",
"value": "555-3620"
}
],
"people": [
{
"uid": "person3",
"classification": "Faculty",
"name": {
"givenName": "Boo",
"nickname": "",
"additionalName": "",
"familyName": "Far"
},
"primaryTitle": "Part Time Worker",
"phones": [
{
"type": "Work",
"value": "555-1617"
},
{
"type": "Mobile",
"value": "555-1508"
}
],
"photo": {
"small": "/__media__/photos/fooz_portrait_small.jpg",
"medium": "/__media__/photos/fooz_portrait_medium.jpg",
"large": "/__media__/photos/fooz_portrait_large.jpg"
}
},
{
"uid": "person4",
"classification": "Faculty",
"name": {
"givenName": "Too",
"nickname": "",
"additionalName": "P.",
"familyName": "Mar"
},
"primaryTitle": "Blah",
"phones": [
{
"type": "Work",
"value": "555-3607"
},
{
"type": "Home",
"value": "555-4717"
}
],
"photo": {
"small": "/__media__/photos/Xportrait_small.jpg",
"medium": "/__media__/photos/Xportrait_medium.jpg",
"large": "/__media__/photos/Xportrait_large.jpg"
}
}
]
}
]
You have an array of objects that each have a people property in them and that property value is an array.
Thus you need to use nested ng-repeat to first loop over the main array and within each iteration of that repeat, loop over the inner array
<ul ng-repeat="item in people">
<li ng-animate="'animate'" ng-repeat="person in item.people | filter: ...">
I am trying to parse this JSON that I have assigned to a javascript variable but I am having a hard time looping through it due to it having multiple levels
<script type="text/javascript">
var varJson = {
"d": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"type": "AlfWebApiInfrastructure.Poco.Office"
},
"Agency": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Agency"
}
},
"Advertiser": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Advertiser"
}
},
"Contacts": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 59980,
"jobId": 1000105450,
"mask": 67108863,
"name": "Name",
"jobtitle": "Job Title",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
},
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 64085,
"jobId": 1000105448,
"mask": 67108863,
"name": "name",
"jobtitle": "jobtitle",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
}
]
},
"id": 100013449,
"companyId": 1787,
"addressLine1": "addressLine1",
"addressLine2": "",
"addressLine3": "",
"addressLine4": "",
"addressLine5": "addressLine5",
"postCode": "postCode",
"regionId": "regionId",
"countyId": "countyId",
"tvAreaId": "L",
"telephone": "telephone",
"fax": "fax8",
"countryId": "countryId",
"email": "email",
"isdn": null,
"mask": 66060287
}
]
}
};
$(document).ready(function () {
//var parsed = JSON.parse(varJson);
alert(varJson);
});
</script>
I tried using this:
$.each(varJson, function (index, item) {
alert(item);
});
But it just says object in my alert.
try this,
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
traverse(v);
});
}
else {
alert(jsonObj);
}
}
$(document).ready(function () {
traverse(varJson);
});
http://jsfiddle.net/satpalsingh/hXEr8/
with reference of Traverse all the Nodes of a JSON Object Tree with JavaScript
You don't need to parse it in your example.
Use console.log instead of alert and you will the the object in your web inspector.
If you do want to alert do something like this
alert(varJson.d.results[0].__metadata.id)