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.
Related
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>
This question already has answers here:
Update field in exact element array in MongoDB
(5 answers)
Closed 4 years ago.
I'm trying to update a specific field using mongoose in Node.js, this is my JSON data:
{
"farms": [
{
"extension": {
"extension": 30,
"measure": "Hectares"
},
"animals": [],
"outs": [],
"plans": [],
"_id": "5ade19a531db34383b3e0bed",
"name": "Farm 2",
"updatedAt": "2018-04-23T17:36:37.680Z",
"createdAt": "2018-04-23T17:36:37.680Z"
},
{
"extension": {
"extension": 30,
"measure": "Hectares"
},
"animals": [],
"outs": [],
"plans": [],
"_id": "5ade19c831db34383b3e0bef",
"name": "Farm 3",
"updatedAt": "2018-04-23T17:37:12.307Z",
"createdAt": "2018-04-23T17:37:12.307Z"
}
],
"_id": "5ade19a5c47476697ec0d155",
"username": "john99",
"__v": 0,
"createdAt": "2018-04-23T17:36:37.680Z",
"updatedAt": "2018-04-23T17:37:12.307Z"
}
I want to update the name field of the "Farm 2". This is the code that I'm using to update:
exports.update = (req, res) => { // fix me
User.update (
{ username: 'john99',
farms: {
$elemMatch: { _id: "5ade19a531db34383b3e0bed" } }
},
{ $set: {
farms: { name: "Farm 99" } } }
)
.then(farm => {
if (!farm) {
return res.status(404).send({
message: "Farm not found with ID " + req.params.idFarm
});
}
res.send(farm);
})
.catch(err => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Farm not Found with ID " + req.params.idFarm
});
}
return res.status(500).send({
message: "Error Updating User with ID " + req.params.idFarm
});
});
};
This is the output of the code above:
{
"farms": [
{
"animals": [],
"outs": [],
"plans": [],
"_id": "5ade1b9c7213483b1b38b60f",
"name": "Farm 99"
}
],
"_id": "5ade19a5c47476697ec0d155",
"username": "john99",
"__v": 0,
"createdAt": "2018-04-23T17:36:37.680Z",
"updatedAt": "2018-04-23T17:45:00.822Z"
}
As you can see, when I try to update the name field, all the farms of that user are deleted and only leave a farm but with incomplete data (without the extension field, createdAt, updatedAt),
How to fix it?
It should resolve your problem!
User.update({'_id': ObjectId('5ade19a5c47476697ec0d155'),
'farms._id' : '5ade19a531db34383b3e0bed'},
{$set: {'famrs.$.name': 'farm 99'}}
).then(farm =>{....});
I am using Microsoft Bot Framework for my facebook messenger bot. I want to load the dialog data from json files instead of hard coding in the js file. I would like to configure the next step in the dialog, based on result from the "current" step, which is part of the json file configuration, something like this.
{
"name": "welcome",
"type": "waterfall",
"steps": [
{
"id": 0,
"data": [
{
"type": "text",
"value": "Hey, It's nice to meet you."
},
{
"type": "quickReplies",
"value": "What do you want to do next?",
"options": [
{
"text": "some option 1",
"value": "option1"
},
{
"text": "some option 2",
"value": "option2"
}
]
}
],
"next": [
{
"result": "option1",
"action": "goto step 2"
},
{
"result": "option2",
"action": "goto step 5"
}
]
}
]
}
I would like to process all the incoming messages and respond with correct dialog or correct step in the dialog for the user.
I am trying something like this;
handleMessage = function (session) {
var step = session.dialogData["BotBuilder.Data.WaterfallStep"] || 0;
// check response data from previou step and identify the next step.
// set the waterfall step id
session.dialogData["BotBuilder.Data.WaterfallStep"] = 2;
session.send("Hello");
}
var bot = new builder.UniversalBot(connector, function (session) {
handleMessage(session);
})
.set('storage',tableStorage);
With this code, I am always getting step as zero for session.dialogData["BotBuilder.Data.WaterfallStep"] even after setting this to a different number.
Also, as soon as I set the waterfall step number, all other state data that is stored in my table storage for this conversation is gone.
Storage data before setting waterfall step:
{
"BotBuilder.Data.SessionState": {
"callstack": [
{
"id": "*:/",
"state": {
"BotBuilder.Data.WaterfallStep": 0
}
},
{
"id": "*:welcome",
"state": {
"BotBuilder.Data.WaterfallStep": 1
}
},
{
"id": "BotBuilder:prompt-text",
"state": {
"options": {
"prompt": {
"type": "message",
"agent": "botbuilder",
"source": "facebook",
"address": {
"id": "mid.$cAAAlr-0LRH9niO21L1hV6hs83GuJ",
"channelId": "facebook",
"user": {
"id": "XXXX",
"name": "XXXX"
},
"conversation": {
"isGroup": false,
"id": "XX"
},
"bot": {
"id": "XXX",
"name": "XXX"
},
"serviceUrl": "https://facebook.botframework.com"
},
"text": "what do you want to next"
//ignored for simplicity
},
"promptAfterAction": true,
"libraryNamespace": "*"
},
"turns": 0,
"lastTurn": 1517594116372,
"isReprompt": false
}
}
],
"lastAccess": 1517594112740,
"version": 0
}
}
After I set the waterfall step:
{
"BotBuilder.Data.SessionState": {
"callstack": [
{
"id": "*:/",
"state": {
"BotBuilder.Data.WaterfallStep": 2
}
}
],
"lastAccess": 1517602122416,
"version": 0
}
}
Interestingly the step number is saved to the database (but in session state) but my "session" variable do not have this value anywhere. Also, even after configuring custom state service, the serviceUrl is still https://facebook.botframework.com which I thought is the default state service used if there is no state service set for the bot.
Per your code, as your bot actually contains only one waterfall step: handleMessage(session);, which raised your issue. You can consider to create multiple dialogs from json configration instead of complex waterfall steps.
Here is my quick test, for your information:
const json = `
[{
"name": "welcome",
"type": "waterfall",
"steps": [
{
"id": 0,
"data": [
{
"type": "text",
"value": "Hey, It's nice to meet you."
},
{
"type": "quickReplies",
"value": "What do you want to do next?",
"options": [
{
"text": "some option 1",
"value": "option1"
},
{
"text": "some option 2",
"value": "option2"
}
]
}
],
"next": [
{
"result": "option1",
"action": "dialog2"
},
{
"result": "option2",
"action": "dialog3"
}
]
}
]
},{
"name":"dialog2",
"type": "waterfall",
"steps": [
{
"data": [
{
"type": "text",
"value": "Hey, this is dialig2."
}]
}
]
},{
"name":"dialog3",
"type": "waterfall",
"steps": [
{
"data": [
{
"type": "text",
"value": "Hey, this is dialig3."
}]
}
]
}]
`;
const generateSignleStep = (step) => {
return (session, args, next) => {
step.forEach(sentence => {
switch (sentence.type) {
case 'quickReplies':
let choices = sentence.options.map(item => {
return item.value
});
let card = new builder.ThumbnailCard(session)
.text(sentence.value)
.buttons(sentence.options.map(choice => new builder.CardAction.imBack(session, choice.value, choice.text)))
let message = new builder.Message(session).addAttachment(card);
builder.Prompts.choice(session, message, choices);
break;
case 'text':
default:
session.send(sentence.value)
break;
}
})
}
}
const generatenextAction = (actions) => {
return (session, args, next) => {
const response = args.response;
actions.map(action => {
if (action.result == response.entity) {
session.beginDialog(action.action);
}
})
}
}
const generateWaterfallSteps = (steps) => {
let waterfall = [];
steps.forEach(step => {
waterfall.push(generateSignleStep(step.data));
if (step.next) {
waterfall.push(generatenextAction(step.next));
}
});
return waterfall;
}
var bot = new builder.UniversalBot(connector);
const jsonobj = JSON.parse(json);
jsonobj.forEach(dialog => {
bot.dialog(dialog.name, generateWaterfallSteps(dialog.steps))
.triggerAction({
matches: new RegExp(dialog.name, "g")
})
});
The result is:
I am using following NodeJs code to get the JsonObject:
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index];
}
res.send(resp);
});
Getting output :
{
"emp1": {
"cas": {
"0": 637861888,
"1": 967242753
},
"flags": 0,
"value": {
"eid": "10",
"ename": "ameen",
"gender": "male",
"designation": "manager",
"country": "Singapur",
"reportee": "Suresh",
"salary": 50000,
"picture": "ameen.jpg"
}
},
"emp2": {
"cas": {
"0": 721747968,
"1": 430939000
},
"flags": 0,
"value": {
"eid": "2",
"ename": "shanmugapriya",
"gender": "female",
"designation": "programmer",
"country": "England",
"reportee": "shruti",
"salary": 14250,
"picture": "priya.jpg"
}
}
}
What I want to do is, I want to display only value key. Can anybody help me how to do this.
Thanks in advance.
Do you mean you want to display only value and key? If so the code below will put only value into the result
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index].value;
}
res.send(resp);
});
The result response will be
{
"emp1":{
"eid":"10",
"ename":"ameen",
"gender":"male",
"designation":"manager",
"country":"Singapur",
"reportee":"Suresh",
"salary":50000,
"picture":"ameen.jpg"
},
"emp2":{
"eid":"2",
"ename":"shanmugapriya",
"gender":"female",
"designation":"programmer",
"country":"England",
"reportee":"shruti",
"salary":14250,
"picture":"priya.jpg"
}
}
UPDATE: Your question was really ambiguous. I think you would need to use Couchbase Views here. Docs http://docs.couchbase.com/couchbase-sdk-node-1.2/#querying-a-view. Assuming that you will build the view _design/employees/_view/all with the following map function:
function(doc, meta) {
emit(meta.id, doc);
}
Your node.js code will look like this
var view = bucket.view('employees', 'all');
view.query(function(err, results) {
res.send(results);
});
I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}