In Koa.js [ObjectObject] while console.log("ctx : "+ ctx.request.body); but if console.log("ctx : ", ctx.request.body); like this it prints JSON - koa

I am trying to console.log("ctx : "+ ctx.request.body);
To view what is in the JSON that received when tried it shows ctx : [object Object].
But if I console.log("ctx : ", ctx.request.body); like this it prints the JSON correctly
without + in console.log().
I want to know what is the reason behind this logic

When you use someString + someObject, when the result is a new string. The object must be converted to a string first before the new string can be created.
Whenever an object is cast to a string in Javascript, the result is [object Object].
To see this behavior you can also.
const obj = {};
const str = obj.toString(); // convert to string
console.log(str);

If you want to have a formatted json output you also can do the following:
console.log("ctx:");
console.log(JSON.stringify(ctx.request.body, null, 2);

Related

Fetch the JSONobject value to a variable which is inside the dynamically generated JSONobject

We have below JSON response which has dynamically getting one of the JSONobject which has other objects inside. Tried some of the solutions provided here, but unable to get the values, every time getting 'null'.
{
"Result": {
"12987654": {//this value 1298.. is dynamically getting generated at every response.
"Tests1": {
"test1": -0.85,
"test2": 0.016,
"tests3": "FAIL"
},
"Tests2": {
"test21": "PASS",
"test22": "PASS",
"test23": "FAIL"
}
}
}
}
Now Trying to get value of inside this dynamically (1298..) generating object, like Tests2.teset21.
If tried as
JSONPath js.get("Results.1298.Tests1.test1")//able to get the value. however here 1298 is hardcoded and this value changes in the next run.
If tried as below, getting value as null.
import com.google.gson.JsonObject;
JsonObject jsonObjectResponse = (JsonObject) new JsonParser().parse(responseInString);
JsonObject Result = jsonObjectResponse.get("loanResult").getAsJsonObject();
SysOut(Result)//gives null
OR, trying below also gives null
JsonElement jelement = new JsonParser().parse(responseInString);
JsonObject ResultObj = jelement.getAsJsonObject();
System.out.println("ResultObj value is: " + loanResultObj.get("tests21"));
Please guide how to get value inside of dynamically generating Jsonobject.
Finally after many attempts, could understand using Gson to get the value. For my issue, the id which dynamic goes from Request. With below code could solve issue:
Gson gsonResp = new Gson();
String responseInString = response.asString();
JsonObject jsonObjectNewResponse = gsonResp.fromJson(responseInString, JsonObject.class);
String test12 = jsonObjectNewResponse.getAsJsonObject("Result").getAsJsonObject(<dynamicID which is been extracted from Req in the form of String>). getAsJsonObject("test1").get("test12").getAsString();

Unable to cast object of type ‘System.String’ to type ‘AuthBotES.ReturnIntents’

Currently I had integrate LUIS with Bot Framework v4.
When I search for result match with Intent,
the Bot return me with this Error:
Error : Unable to cast object of type ‘System.String’ to type ‘AuthBotES.ReturnIntents’.
My Source code as below:
if (stepContext.Result != null)
{
var result = (ReturnIntents)stepContext.Result;
var msg = $"{result}";
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
}
and my ReturnIntents classes.
public class ReturnIntents
{
public string Intent { get; set; }
public double Score { get; set; }
public string Entities { get; set; }
}
A few issues here:
The first code block you posted looks to be for handling the result of a dialog, not for processing a LUIS result.
The cast from string to ReturnIntents will always fail.
Even if your cast of stepContext.Result to ReturnIntents did work, your msg variable would only contain namespace.to.class.ReturnIntents (the string representation of the object type, not the string representation of the objects properties.
Your msg variable is redundant.
I will address these in the order that they occur.
1 - Incorrect code block
This block of code looks suspiciously like code used to process a dialog and here e.g.:
var result = (bool)stepContext.Result;
Rather than the code for handling a LUIS result e.g.:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync(dc.Context, CancellationToken.None);
2 - Casting error
The error is telling you that it doesn't know how to convert a string object to a ReturnIntents object. To convert the string to your object you could use a couple of methods:
Use the NewtonSoft.Json NuGet package to allow you to turn the JSON string into your object as explained here.
2) A user defined type conversion as detailed in the official docs here and explained in this answer.
This error is a red herring in terms of your solution because I believe you're accidentally copied in the wrong block of code.
3 - Incorrect ToString behaviour
To get the string value of a ReturnIntents you will need to override the ToString method for the class and write your own custom implementation.
4 - Redundant cast
This:
// We know that this cast fails, and that stepContext.Result is a string
var result = (ReturnIntents)stepContext.Result;
// This will only return <namespace.path>.ReturnIntents (if the cast above works)
var msg = $"{result}";
// Passing in message msg isn't required, we can just pass in stepContext.Result
await stepContext.Context.SendActivityAsync(MessageFactory.Text(msg), cancellationToken);
Becomes:
var result = stepContext.Result;
await stepContext.Context.SendActivityAsync(MessageFactory.Text(result), cancellationToken);
So what I actually think you actually want is the following:
var dispatchResult = await cognitiveModels.DispatchService.RecognizeAsync<ReturnIntents>(dc.Context, CancellationToken.None);
Which will send the user's input off to LUIS, and deserialize the response into a ReturnIntents object.
Edit to provide solution to the OP
The ExecuteLuisQuery method called here, and defined here returns a ReturnIntents object.
This object is passed as an option to the ReturnIntentDialog here. Because this comes through as an instance of the object type you have a few options inside your FinalStepAsync method here to turn your options object into a ReturnIntents object.:
Casting
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = (ReturnIntents)stepContext.Options;
}
Deserializing
using Newtonsoft.Json;
ReturnIntents returnIntents = null;
if (stepContext.Options is ReturnIntents)
{
returnIntents = JsonConvert.DeserializeObject<ReturnIntents>(JsonConvert.SerializeObject(stepContext.Options));
}

NSDictionary to Json in Xamarin.iOS

I am trying to convert the NSDictionary into Json using NSJsonSerialization.Serialize. But i am not getting expected output
Code in Xamarin.iOS
var dictionary = new NSDictionary(
new NSString("userName"), new NSString("450012"),
new NSString("password"), new NSString("Abc134"),
new NSString("companyId"), new NSString("CM1")
);
request.Body = NSJsonSerialization.Serialize(dictionary, 0, out error);
the problem is that value of dictionary variable is showing
{{password":Abc134,companyId:CM1,userName:450012}}
instead of
{password:Abc134,companyId:CM1,userName:450012}
it is adding one curly braces at the front and back
is there any way to generate proper json string for user input values
There's nothing wrong with your json. If you print it in the console you will see that the value being printed is the value you expect.
{"password":"Abc134","companyId":"CM1","userName":"450012"}
Give it a try with:
Console.WriteLine($"{json}");
If you really, really want to get rid of of that "extra" curly braces just convert the result into string.
var jsonString = json.ToString();
The above should do the work.
I would just suggest you changing your method to this:
var json2 = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);
Using the PrettyPrinted option.
Hope this helps.-
Yes, you can try to create a custom object to serialize. Create a simple plain object to hold the data you want.
User user = new User() {
UserName = "JohnDoe",
Password = "xxx",
CompanyId = 01
};
request.Body = NSJsonSerialization.Serialize(user, 0, out error);
Then serialize it and you will see the proper json well formed.

How to write inresponse in indesign scripts

I am running this script for getting all form fields of a indd file.
var _ALL_FIELDS = "";
var allFields = myDocument.formFields;
for(var i=0;i<allFields.length;i++){
var tf = allFields[i];
alert(tf.id);
alert(tf.label);
alert(tf.name);
alert(_ALL_FIELDS = _ALL_FIELDS +\",\"+ tf.name);
}
What i have done is, created a soap-java based client and calling the runscript method.
Now i am able to get these fields but how to send these fields back to the client i.e. how to write this in response and then at client side how to read it from response.
Code for calling runscript method is:-
Service inDesignService = new ServiceLocator();
ServicePortType inDesignServer = inDesignService.getService(new URL(parsedArgs.getHost()));
IntHolder errorNumber = new IntHolder(0);
StringHolder errorString = new StringHolder();
DataHolder results = new DataHolder();
inDesignServer.runScript(runScriptParams, errorNumber, errorString, results);
Also I have found in docs that runScript method returns RunScriptResponse but in my case it's returning void.
http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/indesign/sdk/cs6/server/ids-solutions.pdf
It looks like you want to return an array of formField names. You could take advantage of the everyItem() collection interface method in your javascript:
var result = myDocument.formFields.everyItem().name;
result;
The javascript will return the last value in the called script, so just to make it completely obvious, the last line is just the value to be returned.
On the Java side, the runScript method is passing the results variable as the 4th parameter, and that's where you'll find your response. So, after your code snippet, you might have something like this:
List<String> formFieldNames = new ArrayList<String>();
if (results.value.getData() != null) {
Data[] resultsArray = (Data[]) results.value.getData();
for (int i = 0; i < resultsArray.length; i++) {
formFieldNames.add(resultsArray[i].getData().toString());
}
}

Json.Net for serializing an object graph

I was using the .Net built in JavaScriptSerializer() to Serialize a JSON string coming from a webpage.
I heard that Newtonsoft.Json.Net have a better serializer, so I thought I would give it a try.
I load my json string, here is a sample.
jsonString = "{\"jName\":\"MB-CEF3-4\",\"StartDate\":\"08/20/2013 00:00\",\"EndDate\":\"08/29/2013 00:00\",\"JType\":\"General\",\"SetupParams\":[
{\"Name\":\"PTitle\",\"Title\":\"01. Period Title\",\"Type\":\"text\",\"Value\":\"TestName\"},
{\"Name\":\"PStart\",\"Title\":\"02. Period Start\",\"Type\":\"datetime\",\"Value\":\"08/20/2013\"},
{\"Name\":\"Target\",\"Title\":\"03. Target\",\"Type\":\"int\",\"Value\":\"1\"},
{\"Name\":\"URL\",\"Title\":\"04. Completion Report URL\",\"Type\":\"url\",\"Value\":\"http://www.example.com\"},
{\"Name\":\"FormTitle\",\"Title\":\"05. Form Title\",\"Type\":\"text\",\"Value\":\"ct\"},
{\"Name\":\"nvTypes\",\"Title\":\"{B6E71787-EB51-45CF-B408-552F79AF2E7B}\",\"Type\":\"nvc\",\"Value\":\"Use of nv tools\"}, {\"Name\":\"NVCoachingTypes\",\"Title\":\"\",\"Type\":\"nvc\",\"Value\":\"\"}]}";
JavaScriptSerializer scs = new JavaScriptSerializer();
Dictionary<String, Object> aps = (Dictionary<String, Object>)scs.DeserializeObject(ActSetupConfigs);
I then would pass this Dictionary into another worker class, where it is deserialized..
I was using: var parameters = ((object[])Parameters["SetupParams"]);
and it would load the an array of objects.
I tried to do the same with Json.Net
Dictionary<String, Object> aps = JsonConvert.DeserializeObject<Dictionary<String, Object>>(ActSetupConfigs);
but when I try to deserialize it I don't get an array of objects, instead the sub collection of the array is just a string....so it throws an exception. How can I use Json.net to serialize all the sub-collections?
The sub-collection of the SetupParams array is not a string, it is a JToken, which is a generic container object that JSON.Net uses to hold a JSON structure. Fortunately, it is easy to extract values from a JToken. Try using this code instead.
JToken aps = JToken.Parse(jsonString);
foreach (JToken param in aps["SetupParams"])
{
Console.WriteLine("Name: " + param["Name"].Value<string>());
Console.WriteLine("Title: " + param["Title"].Value<string>());
Console.WriteLine("Type: " + param["Type"].Value<string>());
Console.WriteLine("Value: " + param["Value"].Value<string>());
Console.WriteLine();
}
You can parse the above json response using json.net like,
dynamic initialresp=JValue.Parse(jsonString);
string jname=Convert.ToString(initialresp.jname);
...
...
dynamic setupparams=JArray.Parse(Convert.ToString(initialresp.SetupParams));
foreach(var item in setupparams)
{
string name=Convert.Tostring(item.Name);
string title=Convert.Tostring(item.Title);
...
...
}
Hope this helps.

Resources