Microsoft Bot Framework using variables in Prompts.choice - json

My current code for asking a yes/no question is
builder.Prompts.choice(session, q15, "Yes|No", { listStyle: builder.ListStyle.button });
I want to store the strings "Yes" and "No" in a JSON file and access them by their variable names, instead of hardcoding it. How can I do that?

As the definition of choice():
choice(session: Session, prompt: TextOrMessageType, choices: string|Object|string[]|IChoice[], options?: IPromptChoiceOptions): void;
You can pass a string array as the choices. So please consider the following code snippet:
//assume you have read the json string from a file and use it as following
const json_string = `{
"VARIABLE_YES":"Yes",
"VARIABLE_NO":"No"
}`;
const json_obj = JSON.parse(json_string);
builder.Prompts.choice(session, 'Make a choice', [json_obj.VARIABLE_YES, json_obj.VARIABLE_NO], {
listStyle: builder.ListStyle.button
});

Related

Replace a + with a space in a string

I have a Typescript project where I am converting URL parameters to a JSON object.
The problem is that a value is concatenated with a '+', how can I replace this symbol with a space?
This is the URL:
let paramUrl = 'type=MERCEDES+BENZ'
This is what I do:
let replace = JSON.parse('{"' + paramUrl.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
This is what it returns:
{type: "MERCEDES+BENZ"}
This is what I need:
{type: "MERCEDES BENZ"}
Unless you're very skilled with regular expressions I would strongly discourage using them for situations like this. In fact, any kind of explicit manipulation of characters here is going to be harder to debug and maintain than just using available JavaScript APIs to convert your url search params string into a plain object.
Here's how I'd suggest you proceed, assuming your JS runtime has both the URLSearchParams constructor and the Object.fromEntries() method:
let paramUrl = 'type=MERCEDES+BENZ'
const replace = Object.fromEntries(new URLSearchParams(paramUrl));
console.log(replace) // { "type": "MERCEDES BENZ" }
That's essentially a one-liner that first converts your paramUrl string into an object representing a list of string key-value pairs, and then converts these key-value pairs into a plain object. You're not responsible for maintaining or implementing URLSearchParams or Object.fromEntries(); you just have to use or polyfill them (e.g., this polyfill for URLSearchParams).
Be aware that if your search param string has multiple values for the same key (e.g., foo=bar&foo=baz) that you'll end up with just the latter one, but you can deal with that if you need to by switching from Object.fromEntries() to some more custom iteration.
Playground link to code
Whether your conversion makes sense or not, you may convert your result with this:
const replace = {type: "MERCEDES+BENZ"}
const replacedReplace = JSON.parse(JSON.stringify(replace).replace('+', ' '))
console.log(replacedReplace)
Or manipulate the value directly:
let replace = {type: "MERCEDES+BENZ"}
replace.type=replace.type.replace('+',' ')
console.log(replace)
try this
let paramUrl = 'type=MERCEDES+BENZ';
let arr=paramUrl.replaceAll("+"," ").split("=");
let obj={[arr[0]]:arr[1]}; // {type: "MERCEDES BENZ"}
or in one line
let obj= paramUrl.replaceAll("+"," ").split("=")
.reduce( (key,value) => { return { [key] : value}; } ); // {type: "MERCEDES BENZ"}

How to update the local json field in flutter

I am new to flutter and dart I read a lot of web article and documentation but didn't able to figure out how to update JSON field I have a local JSON file like
{
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}]}
I want to update the filed favorite to true in JSON file Is there any way to do this
You Can parse the JSON like this
Map<String, dynamic> data = jsonDecode(jsonString);
And if you want to make each favorite true then You can use looping like this
(data["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
if you want to set a single object value true then you need to pass the position like this
(data["quotes"] as List<dynamic>)[position]['favorite'] = true;
Addition
Here is the link to encode and decode the JSON
You can use a forEach loop on the quotes list in the JSON and set favourite to true inside it. I'm assuming you have a parsed your String data into JSON using jsonDecode or json.decode.
If not, here's a link on how to parse JSON data in Dart.
Consider the below code -
Map<String, dynamic> jsonData = {
"category": "Happiness",
"quotes":[
{
"quote":"I hope you will find a reason to smile",
"favorite":false
},
{
"quote":"Sometimes your joy is the source of your smile, but sometimes your smile can be the source of your joy.",
"favorite":false
}
]};
(jsonData["quotes"] as List<dynamic>).forEach((item) {
item["favorite"] = true;
});
You can also alternatively use shorthand syntax for the forEach loop function like below -
(jsonData["quotes"] as List<dynamic>).forEach((item) => item["favorite"] = true);
first take this json array to any variable and then understand the hierarchy .
e.g "jsonArr" is the array that hold that data then ..
jsonArr['quotes'][0]['favorite'] = true;
or you can put this in a for loop and traverse this loop to the length of the json array.
You can use the following method. The field favorite is changed to true when the button is pressed.
FlatButton(
child: Text('Add Favourite'),
onPressed: (){
myJson['quotes'][myIndex]['favorite'] = true;
})

Angular 7 HTTP GET send JSON object as a parameter

Im trying to send a json structure to a rest service from angular doing something like this
let test5var = {
"test5var1": {
"test5var2": "0317",
"test5var3": "9556"
},
"test5var4": "123",
"test5var": "0000046"
}
let dataPrincipalBlnc = {"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}};
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let params = new HttpParams().set("requestData", dataPrincipalBlnc.toString()).set("authenticationType", this.authType);
return this.http.get(this.url, {params: params});
The result of the request should look like follows:
https://example.com/test?authenticationType=cookie&requestData=%7B%test%22:%7B%22test1%22:%7B%22test2%22:%220317%22,%22test3%22:%7B%22IDIOMA_ISO%22:%22+en%22,%22DIALECTO_ISO%22:%22US%22%7D,%22channel%22:%22INT%22%7D,%22input%22:%7B%22test5%22:%7B%22test5var1%22:%7B%22test5var2%22:%220317%22,%22test5var3%22:%229556%22%7D,%22test5var4%22:%22123%22,%22test5var5%22:%220000986%22%7D%7D%7D%7D
But it is currently sent as:
https://example.com/test?requestData=%5Bobject%20Object%5D&authenticationType=cookie
Any ideas how can I send the json object to looks as the first request? Do I need to manually convert the json to a valid uri format?
In angularJS is working fine just using the following code:
var data = {
"test1": {
"test2": {
"test3": "0317",
"test4": {
"IDIOMA_ISO": " en",
"DIALECTO_ISO": "US"
},
"channel": "INT"
},
"input": {
"test5": test5var
}
}
};
$http.get(url, {
params: {
authenticationType: authType,
requestData: data
}
}).then(success(deferred), error(deferred));
I have also tried using the following code but the result is adding more characters and the backend is failling because it says the JSON is not in a valid format:
encodeURIComponent(JSON.stringify(dataPrincipalBlnc)
?requestData=%257B%2522test%2522%253A%257B%2522test1%2522%253A%257B%2522test2%2522%253A%25220317%2522%252C%2522test3%2522%253A%257B%2522IDIOMA_ISO%2522%253A%2522%2520en%2522%252C%2522DIALECTO_ISO%2522%253A%2522US%2522%257D%252C%2522channel%2522%253A%2522INT%2522%257D%252C%2522input%2522%253A%257B%2522test5%2522%253A%257B%2522test5var1%2522%253A%257B%2522test5var2%2522%253A%25220317%2522%252C%2522test5var4%2522%253A%25229556%2522%257D%252C%2522test5var4%2522%253A%2522123%2522%252C%2522test5var5%2522%253A%25220003303%2522%257D%257D%257D%257D&authenticationType=cookie
Thanks
Regards
Any JSON object being passed to the service should be sent via response body.
You should add valid string parameters only in the url.
Also there is url size limitation for most browsers, so bigger object may lead you to the long url problem.
You are seeing the requestData=%5Bobject%20Object%5D&authenticationType=cookie because it cannot put a JSON object in url query string.
Some characters cannot be part of a URL (for example, the space) and some other characters have a special meaning in a URL: for example, the character # can be used to further specify a subsection (or fragment) of a document; the character = is used to separate a name from a value. A query string may need to be converted to satisfy these constraints. This can be done using a schema known as URL encoding.
Use JSON.stringify when you have a JavaScript Object and you want to convert it to a string (containing a JSON text). This is called serialization.
Regardless to JSON:
Use encodeURIComponent whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.
Still i would prefer to send the object in the request body.
So in your case use:
let params = new HttpParams()
.set("requestData", encodeURIComponent(JSON.stringify(dataPrincipalBlnc)))
.set("authenticationType", this.authType);
Adding to #nircraft answer (which is very elaborate and good) this implementation seems to does the trick for you,
let test5var = {
"test5var1": {
"test5var2": "0317",
"test5var3": "9556"
},
"test5var4": "123",
"test5var": "0000046"
}
let dataPrincipalBlnc = '{"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}}';
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let params = new HttpParams().set("requestData", encodeURIComponent(dataPrincipalBlnc)).set("authenticationType", this.authType);
return this.http.get(this.url, {params: params});
In Javascript you can basically enclose a string in '' or "".
When you don't enclose the string specifically I believe it is enclosed with "", thus making your JSON response in need of escape characters when you use stringify.
Enclosing the string like this will make sure that the double quotes will make sure that it won't need escape characters.
Let me know if you have any questions.
I just fixed the issue by defining the data as an object and using just the JSON.stringify:
let dataPrincipalBlnc: object;
let dataPrincipalBlnc = {"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}};
let params = new HttpParams().set("requestData", JSON.stringify(dataPrincipalBlnc)).set("authenticationType", this.authType);
Thanks for your help
Regards

Asserting entire response body in post man

I recently started working on spring boot projects.
I am looking for a way to assert the entire response of my API.
The intention of this is to reduce the testing time taken for the API.
Found A few solutions mentioned below, but nothing helped me resolve the issue.
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
When I put the entire response body as an argument, I get the below errors.
Unclosed String
2.
3.
If you want to use the same type of quotes you defined the string with inside it, you have to escape them:
'string with "quotes"'
"string with 'quotes'"
'string with \'quotes\''
"string with \"quotes\""
You probably want to put your json in single quotes as they are not allowed by json itself.
You could try setting the response as a variable and then assert against that?
var jsonData = pm.response.json()
pm.environment.set('responseData', JSON.stringify(jsonData))
From here you can get the data JSON.parse(pm.enviroment.get('responseData')) and then use this within any test to assert against all of the values.
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})
My reasoning is that you’re trying to assert against JSON anyway but doing as a plain text string.
Or you could assert against the values separately like this:
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData[0].employeeName).to.equal("tushar")
pm.expect(jsonData[0].phNum).to.equal(10101010)
})
Depending on the JSON structure you may not need to access an array of data and the [0] can be dropped.

How can I pretty-print JSON using node.js?

This seems like a solved problem but I am unable to find a solution for it.
Basically, I read a JSON file, change a key, and write back the new JSON to the same file. All works, but I loose the JSON formatting.So, instead of:
{
name:'test',
version:'1.0'
}
I get
{name:'test',version:'1.1'}
Is there a way in Node.js to write well formatted JSON to file ?
JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:
var fs = require('fs');
fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
"a": 1,
"b": 2,
"c": 3,
}
*/
See the JSON.stringify() docs at MDN, Node fs docs
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
If you just want to pretty print an object and not export it as valid JSON you can use console.dir().
It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
const jsonString = `{"name":"John","color":"green",
"smoker":false,"id":7,"city":"Berlin"}`
const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
Under the hood it is a shortcut for console.log(util.inspect(…)).
The only difference is that it bypasses any custom inspect() function defined on an object.
If you don't want to store this anywhere, but just view the object for debugging purposes.
console.log(JSON.stringify(object, null, " "));
You can change the third parameter to adjust the indentation.
I know this is old question. But maybe this can help you 😀
JSON string
var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';
Pretty Print JSON
JSON.stringify(JSON.parse(jsonStr), null, 2);
Minify JSON
JSON.stringify(JSON.parse(jsonStr));
what about this?
console.table(object)
Another workaround would be to make use of prettier to format the JSON.
The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.
const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));
if prettify is name value pairs on new lines then specifying number of spaces in stringify didn't work for me the only thing that worked for me was
await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;