Using JSON to convert an array from C# to Javascript - javascript

I have been struggling with consuming c# code converted to the javascript angular navigation tree structure. The code is correctly converted because when I hard code the returned json value my app works. However, when I try to set a variable equal to the returned get value the app does not work. Is there some kind of conversion I am missing between the get command and entering it into my treeContents?
$scope.deviceNavCollection = DeviceSvc.DeviceNavCollection.get({ deviceId:$scope.currentDeviceID });
var treeData = $scope.deviceNavCollection;
$scope.treeContents = treeData.data;
The format of the data (which matches abn-tree)
{"data":[{"label":"Connection","id":1,"src":"../Device_Common/partials/Connection.html","children":null},............}]}]}
HTML
<abn-tree tree-data="treeContents" on-select="onTreeItemSelected(branch)" select-id="treeSelectId" icon-leaf="icon-file" expand-level="1"></abn-tree>
c#
string strJSON = new JavaScriptSerializer().Serialize(navCollection);
return json;
System.Console.WriteLine("C#: Leaving GetDeviceNavCollection method");
Thanks

The request is asynchronous, you have to wait until it's finished otherwise it will be undefined:
DeviceSvc.DeviceNavCollection.get({ deviceId:$scope.currentDeviceID }).then(function(response) {
$scope.deviceNavCollection = response;
var treeData = $scope.deviceNavCollection;
$scope.treeContents = treeData.data;
});
This is, of course, assuming your DeviceNavCollection service is returning a promise.

Related

Why string get from buffer does not equal to JavaScript String

I am working on a project in which I am using node js and python together. My node js code makes a child process of python code. And I am sending some data from node js to python and also receiving some data back from python to node.
I call my python file like this.
const py = spawn('python', ['file.py', 'some_data']);
and for sending data back from python to node I am using print in python like this.
print("mydata")
and for receiving in nodejs I am using this code.
py.stdout.on('data', async (data) => {
//This data is python string as we can see above
var data_from_python = data.toString();
});
now the problem I am facing is string which come from python does not equal to node js string I have tried this.
data_from_python === "mydata" // false
and also this
data_from_python == "mydata" // false
both returns false.
But when I console the type of both using typeof operator it says string for both.
I want to know what is reason behind and what is the solution if we want to compare them or is there a better way to get data back from python to node. I know this "mydata" string is coming from buffer, python is putting it into the buffer and node is reading it from the buffer, and I think they both are different because one is python string and other is nodejs string, maybe it is because of under the hood both deal or make strings differently.
But what is the exact story behind if anyone one know please share your knowledge.
This is because print in python adds a new line after the data, So instead of getting mydata you will receive mydata\r\n. So you should check for the same in your condition, see below:
const { spawn } = require('child_process')
const py = spawn('python', ['py.py', 'some_data']);
py.stdout.on('data', async (data) => {
console.log(data);
var data_from_python = data.toString();
console.log(data_from_python == "mydata\r\n"); // outputs true
});

POSTMAN - EXPRESS - Modify JSON before writing to file

I have written a POSTMAN call to a server that responds with a list of items in JSON like below:-
{
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
}
I want to make calls to another server using the value of the setID each time and iterate through all of these so that I end up calling the server thousands of times to verify the response from that server. The problem I have is that the second server expects the set id to be in a form where the forward slashes are converted to underscores and the hashes to dots, so
"1/7842/0889#001"
becomes
"1_7842_0889.001"
I have code that converts one to the other in POSTMAN
var jsonData = pm.response.json()
for (var i=0; i<jsonData.setIds.length; i++)
{
var new_j = jsonData.setIds[i].replace (/#/g, ".");
var new_i = new_j.replace (/\//g, "_");
}
})
This works fine line by line it creates the right thing in the console of POSTMAN but obviously what I really need to do is save the entire JSON in the right form to a file and then read from that file line by line using the corrected data. I don't seem to be able to save the data in a file in the right form using my code and I suspect I am missing something simple. Is there a way to write a file line by line from in side postman or in a script and manipulate the data as I'm creating it?
Alternatively I guess I could read from the JSON I have saved i.e. the full response and iterate through that manipulating the data as a pre-request script?
I have tried to do something like this using environmental variables - so in my first call I do:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable('setIds', JSON.stringify(jsonData));
and then in my second call to the express server where I want to send my payload I run a pre-request script that I thought would work using the env variable but this fails as it doesn't seem to like the {...
SyntaxError: Unexpected token {
I think there are probably some neat ways of solving this either doing all of this outside of POSTMAN in javascript but I'm a little lost where to start. Any help appreciated
Would tell you are plaing with content, but not setting it back to JSON object ??
jsonData.setIds[i] = new_i;
can help or you can use 2x replace it in a string and convert back to make it easier (in case there are no / or # somewhere else).
var src = {
"count": 6909,
"setIds": [
"1/7842/0889#001",
"2/4259/0166#001",
"ENT0730/0009",
"9D/11181#002",
"1/9676/0001#001",
"2/4718/0001#004",
"2/1783/0044#001",
"1/4501/0001#001",
"1/2028/0002#002",
"2/3120/0079#001",
"2/1672/0024#001",
"2/3398/0064#001"
//...
]
}
var str = JSON.stringify(src, null, 4);
str = str.replace(/\//g,'_').replace(/#/g,'.');
console.log(str);
var res = JSON.parse(str);
console.log(res);

Odd occurrence in using app.use(parseExpressRawBody())

Maybe this is simple, maybe this is a bug on Parse - would like to know if anyone has had the same problem and a possible solution.
What I'm trying to do:
I'm sending a JSON request from an app called FormEntry to my Parse app
The body comes in like this: json={"someLabel" : "someValue"}
I would like to take the entire body and create a Parse.Cloud.httpRequest over to Zapier to perform some functions.
Now, the problem seems to be this:
On random occasions (i.e. I have no idea why), the body is sent (as shown by the logs) where there is a trailing comma at the end of the last pair in the JSON object. e.g. like this json={"lastLabel" : "lastValue",}
The number of elements in 'normal' and 'incorrect' objects seem to be the same, so it's simply just another comma added. And I have no idea why.
My setup:
Using app.use(parseExpressRawBody()); only and not the standard app.use(express.bodyParser()); which doesn't provide access to the raw body.
Because parseExpressRawBody converts the body to a buffer I need to turn it back into a string to send it in the HTTP request in a meaningful way. Therefore I use: var body = req.body.toString();
When logging this var to the Parse console it looks to be format back from the buffer fine.
And that's about it. Nothing complex going on here but a real annoying bug that I just haven't found a sensible way of understanding. Would SUPER appreciate anyone who has seen this before or who could point me in a direction to focus on.
Just an update on this. Not a solution that answers why there is malformed JSON but a hack to get the right result.
The purpose of the HTTP request was to point over to Zapier so I wrote a Zapier script that would deal with the malformed JSON. Added here for anyone else who needs it.
"use strict";
var Zap = { newSubmission_catch_hook: function(bundle) {
var body = bundle.request.content;
var cleanTop = body.substring(5,body.length);
var cleanChar = cleanTop.length;
var condition = cleanTop.substring(cleanChar-2,cleanChar);
function testCase(condition,cleanTop) {
if (condition != ",}"){
console.log("Everything is fine, returning JSON");
return cleanTop;
}
else {
console.log("Nope! We have an error, cleaning end");
var cleanEnd = cleanTop.substr(0,cleanChar-2) + '}';
console.log("The object now ends with: " + cleanEnd.substr(-10));
return cleanEnd;
}
}
var newBody = JSON.parse(testCase(condition,cleanTop));
return newBody;
}
};

Returning single ID in JSON from a web service

I'm fairly new to working with client-side coding and was wondering what the the best way of returning a single ID from a simple Insert in a web service would be.
Copying code that returns more complex JSON objects, I'm doing the following:
Dim JaggedArray As String()() = New String(0)() {}
Dim i As Integer = 0
JaggedArray(i) = New String() {<insert stmt, returns integer>}
Dim js As New JavaScriptSerializer()
Dim strJSON As String = js.Serialize(JaggedArray)
Return strJSON
I then use the following to access the ID in Javascript (excerpt from the AJAX call):
success: function(data) {
var c = eval(data.d);
var testID = c[0][0];
Surely there's a less clunky way of doing this, right?
And this is a stupid question, but can (and / or should) you put code outside of the Success callback, or is this mandatory?
Surely you can use jqXHR.done An alternative construct to the success callback option, the .done(),
for more info visit http://api.jquery.com/jQuery.ajax/
$.ajax({
//ajax stuff ..
})
.done(function(return){
var output = "hello";
return output;
});

Trying to pull data from parse and render with underscore.js getting empty frields

Trying to pull data from parse.com and use underscore.js I tried using this to build a table of the data. When I run it with hard coded json it works but when I try running it with pulled data returns an empty table.
Parse.initialize("", "");
var allDeals = Parse.Object.extend("Deal");
var query = new Parse.Query(allDeals);
query.find({
success: function(results){
var deals = JSON.stringify(results);
var template = $("#usageList").html();
$("#target").html(_.template(template,{deals:deals}));
},
error: function(error) {
alert('something was wrong');
}
});
Thanks in advance!
Like #mu said it would be easier to see whats in results..
But I have run into this with Parse before. Taking a guess.. You can try this
$('#target').html(_.template(template, { deals: results.models }));
"results" is a backbone collection and "models" holds the array of objects you are after.
Presumably you're getting a JavaScript object of some sort in results in your success callback. Then you serialize that to a JSON string with:
var deals = JSON.stringify(results);
That leaves you with a string in deals and your template probably doesn't know what to do with a string, it probably wants an object or whatever was in results in the first place. Try skipping the stringification and just feed results straight into the template:
$('#target').html(_.template(template, { deals: results }));

Categories