I am trying to get data from a JSON file in ionic app using.
this.http.get('https://track.delhivery.com/api/packages/json/?token=c7ac81cde31a5ea69d38cb098cab16cf7f909062&waybill=2285210000022').map(res => res.json()).subscribe(data => {
this.trackingorder = data;
console.log(this.trackingorder.ShipmentData);
But i am getting error that Shipment is undefined.
My JSON file is of the format
{
"ShipmentData": [
{
"Shipment": {
"Origin": "Bengaluru_Bomsndra_PC (Karnataka)",
"Status": {
"Status": "Delivered",
"StatusLocation": "Cjb_Kovaipudur_Dc (Tamil Nadu)",
"StatusDateTime": "2018-12-20T17:57:28.002000",
"RecievedBy": "",
"Instructions": "Delivered to consignee",
"StatusType": "DL",
"StatusCode": "EOD-38"
},
"PickUpDate": "2018-12-18T19:44:43",
"ChargedWeight": null,
"OrderType": "Pre-paid",
"Destination": "Coimbatore",
"Consignee": {
"City": "Coimbatore",
"Name": "Sayal Krishna",
"Country": "India",
"Address2": [],
"Address3": "",
"PinCode": 641105,
"State": "Tamil Nadu",
"Telephone2": "",
"Telephone1": [
"8667079713"
],
"Address1": [
"A-198,\nTamil annai street,Gandhi nagar,madukarai\nCoimbatore 641105"
]
},
"ReferenceNo": "5160",
"ReturnedDate": null,
"DestRecieveDate": "2018-12-20T07:56:22.518000",
"OriginRecieveDate": "2018-12-18T23:00:58.874000",
"OutDestinationDate": "2018-12-19T00:54:18.663000",
"CODAmount": 0,
"EWBN": [],
"FirstAttemptDate": null,
"ReverseInTransit": false,
"Scans": [
{
"ScanDetail": {
"ScanDateTime": "2018-12-18T00:33:37.614000",
"ScanType": "UD",
"Scan": "Manifested",
"StatusDateTime": "2018-12-18T00:33:37.614000",
"ScannedLocation": "BLR_Kudulu_CP (Karnataka)",
"Instructions": "Consignment Manifested",
"StatusCode": "X-UCI"
}
},
{
"ScanDetail": {
"ScanDateTime": "2018-12-20T17:57:28.002000",
"ScanType": "DL",
"Scan": "Delivered",
"StatusDateTime": "2018-12-20T17:57:28.002000",
"ScannedLocation": "Cjb_Kovaipudur_Dc (Tamil Nadu)",
"Instructions": "Delivered to consignee",
"StatusCode": "EOD-38"
}
}
],
}
}
]
}
Please help me get Shipment from this JSON file.
The exact error I am getting is
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Shipment' of undefined
It depends on which http module you are using.
For "#angular/common/http",
this.http.get('https://yourapi.com').subscribe(data => {
this.trackingorder = data;
console.log(this.trackingorder.ShipmentData);
}
For '#ionic-native/http',
this.http.get('https://yourapi.com').subscribe(data => {
this.trackingorder = JSON.parse(data);
console.log(this.trackingorder.ShipmentData);
}
If your using angular http then replace this line of code in your project.
change this line to
this.trackingorder = data;
Below line
this.trackingorder = data.json();
Should solve your problem. All the best.
I found the following method working .
Inside your .ts file use
this.http.get("https://track.delhivery.com/api/packages/json/?token=c7ac81cde31a5ea69d38cb098cab16cf7f909062&waybill=2285210000022")
.subscribe((userData) => {
console.log("shipment data" +userData);
this.users.push(userData);
});
Inside the HTML file , use the following
<div *ngFor ="let Scan of users[0].ShipmentData[0].Shipment.Scans" class="item h5">
<div *ngIf="Scan.ScanDetail.Scan=='Manifested'">
<h5 style="font-size:12px;color:black;">• {{Scan.ScanDetail.ScannedLocation}}</h5>
</div>
Related
In postman I am able to log in the user and get an accessToken:
Doing Post at http://localhost:3030/authentication I type in:
{
"strategy": "local",
"email": "bob#bob.com",
"password": "bob"
}
and then I get:
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE2NjEzMjgzMDEsImV4cCI6MTY2MTQxNDcwMSwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMyOWMwZTU3LTM5NTctNDUxOS05N2ZmLTRiNDIxOWI2MDQ2YSJ9.tIiRCMqzNg8F4lb1tzfYrOVvc148qRmZrZ7FPouHhKg",
"authentication": {
"strategy": "local",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE2NjEzMjgzMDEsImV4cCI6MTY2MTQxNDcwMSwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMyOWMwZTU3LTM5NTctNDUxOS05N2ZmLTRiNDIxOWI2MDQ2YSJ9.tIiRCMqzNg8F4lb1tzfYrOVvc148qRmZrZ7FPouHhKg",
"payload": {
"iat": 1661328301,
"exp": 1661414701,
"aud": "https://yourdomain.com",
"iss": "feathers",
"sub": "1",
"jti": "329c0e57-3957-4519-97ff-4b4219b6046a"
}
},
"user": {
"id": 1,
"email": "bob#bob.com",
"createdAt": "2022-08-24T08:04:57.464Z",
"updatedAt": "2022-08-24T08:04:57.464Z"
}
}
But then when I try to use accessToken for another POST in Postman, I get:
{
"name": "NotAuthenticated",
"message": "Not authenticated",
"code": 401,
"className": "not-authenticated",
"errors": {}
}
Why is this?
One idea I have is maybe I did this part wrong. I thought I was supposed to add
auth.associateCurrentUser({
idField: "id",
as: "group_admin",
}),
But I was getting an error & found something online that said to change it to this (context below):
setField({
from: "params.user.id",
as: "data.group_admin",
}),
import * as authentication from "#feathersjs/authentication";
// Don't remove this comment. It's needed to format import lines nicely.
const { authenticate } = authentication.hooks;
import { setField } from "feathers-authentication-hooks";
export default {
before: {
all: [authenticate("jwt")],
find: [],
get: [],
create: [
setField({
from: "params.user.id",
as: "data.group_admin",
}),
// auth.associateCurrentUser({
// idField: "id",
// as: "group_admin",
// }),
],
update: [],
patch: [],
remove: [],
},
Do you have any ideas to get the accessToken to work with authentication?
I can post more code if needed.
I want to use datatable to return JSON from txt or some web api.
So, everything works well if data is in following format (coopInformation.txt):
{
"data": [
{
"employer": "Unisys",
"degree": "NETSYS-MS",
"city": "Blue Bell PA",
"term": "20151"
},
{
"employer": "Paychex Inc",
"degree": "INFOST-MS",
"city": "Rochester NY",
"term": "20151"
},
{
"employer": "Paychex Inc",
"degree": "INFOST-MS",
"city": "Rochester NY",
"term": "20151"
}
]
}
This is my jquery call:
$(document).ready(function() {
$('#example').DataTable({
ajax: 'ajax/data/coopInformation.txt',
columns: [
{
data: 'employer'
},
{
data: 'degree'
},
{
data: "city"
},
{
data: "term"
}
]
});
});
But when json object don't start with "data", for example starts with "coopInformation", this call returns an error even if I change columns to coopInformation:
$(document).ready(function() {
$('#example').DataTable({
ajax: 'ajax/data/coopInformation.txt',
columns: [
{
coopInformation: 'employer'
},
{
coopInformation: 'degree'
},
{
coopInformation: "city"
},
{
coopInformation: "term"
}
]
});
});
Uncaught TypeError: Cannot read property 'length' of undefined
at jquery.dataTables.min.js:65
at h (jquery.dataTables.min.js:51)
at Object.success (jquery.dataTables.min.js:52)
at fire (jquery-3.5.1.js:3496)
at Object.fireWith [as resolveWith] (jquery-3.5.1.js:3626)
at done (jquery-3.5.1.js:9786)
at XMLHttpRequest. (jquery-3.5.1.js:10047)
It looks like this libs are predefined to use "data" or I am wrong...
My question is: how to make a simple call like this using something else but not "data". On datatables web, all examples are used with this "data".
Kind regards,
Milan
I currently have a page in JavaScript that fetches data from an API. The problem is that I can't access the service.statusgroup.name object in the response.
I get this error: "TypeError: service.statusgroup is null". But when I remove .name, I don't get any error.
JSON Response:
{
"id": 2,
"title": "Website",
"description": "Website accessibility",
"status": "0",
"statusgroup": {
"id": 1,
"name": "Services", <-- Can't get this
"created_at": "2021-03-14T17:08:15.204Z",
"updated_at": "2021-03-14T17:40:29.739Z"
},
"created_at": "2021-03-14T15:06:18.524Z",
"updated_at": "2021-03-14T17:42:22.235Z"
}
JavaScript Fetch (VueJS):
export default {
name: 'Status',
mounted() {
// Fetch data from API
axios.get('http://localhost:1337/statuspages')
.then((reponse) => {
this.services = reponse.data
})
},
data: function() {
return {
services: null,
}
},
Display of the reponse:
<template v-for="service in services">
<v-list-item :key="service">
{{ service.statusgroup.name }}
</v-list-item>
</template>
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})
I am attempting to use a simple $http.get to a .JSON file, which seems to be found, but when trying to pass the data to the front end, i am seeing an error in my console:
Error: data.unitedkindgom: is undefined
Here's my controller:
app.controller("CityController", function($scope, $http, cityService) {
$scope.UKCities = [];
cityService.getCityData(function(data) {
$scope.UKCities = data.unitedkindgom.CityInfo;
console.log(data.unitedkindgom.CityInfo);
});
My JSON:
unitedkindgom: {
"NoCities": 66,
"Balance": 2103,
"Population": 63705000,
"CityInfo": [
{
"CityName": "London",
"CityPopulation": "7825200",
"Facts": {
"SubFact1": "xzy",
"SubFact2": "xzy",
"SubFact3": "xzy",
"SubFact4": "xzy",
"SubFact5": "xzy"
},
},
{
"CityName": "Manchester",
"CityPopulation": "2584241",
"Facts": {
"SubFact1": "abc",
"SubFact2": "abc",
"SubFact3": "abc",
"SubFact4": "abc"
},
}
],
"SubmitInfo": null,
"FormAction": null,
"FormController": null,
}
Thanks
UPDATE
cityService.getCityData
app.factory('cityService', function($http) {
return {
getCityData: function(done) {
$http.get('/data/city.json')
.success(function(data) { done(data);})
.error(function(error) {
alert('An error has occured');
});
}
}
});
UPDATE
If i remove $scope.UKCities = data.unitedkindgom.CityInfo; and replace console.log(data.unitedkindgom.CityInfo); with console.log(data); I can see all my data in the console window.
If replace console.log(data.unitedkindgom.CityInfo); with console.log(data.unitedkindgom); I see Undefined in the console window.
Using JSONLint, I found out that your JSON is invalid, so it can't be parsed
Below is a valid JSON of your data
{
"unitedkindgom": {
"NoCities": 66,
"Balance": 2103,
"Population": 63705000,
"CityInfo": [
{
"CityName": "London",
"CityPopulation": "7825200",
"Facts": {
"SubFact1": "xzy",
"SubFact2": "xzy",
"SubFact3": "xzy",
"SubFact4": "xzy",
"SubFact5": "xzy"
}
},
{
"CityName": "Manchester",
"CityPopulation": "2584241",
"Facts": {
"SubFact1": "abc",
"SubFact2": "abc",
"SubFact3": "abc",
"SubFact4": "abc"
}
}
],
"SubmitInfo": null,
"FormAction": null,
"FormController": null
}
}
Note that its entirely wrapped in { }, unitedkindgom is wrapped in " " and here and there some excess , are removed.