How to get key values from Html in Flutter? - html

I have the following html string. how to decode this and get key values
<html>
<head></head>
<body>order_id=1289&tracking_id=111028965908&bank_ref_no=916831&order_status="
"Success&failure_message=&payment_mode=Credit Card&card_name=MasterCard&status_code=00&"
"status_message=Approved¤cy=AED&amount=140.0&billing_name=Gx&billing_address=Yd&billing_city=Ud&"
"billing_state=&billing_zip=Uf&billing_country=Andorra&billing_tel=4&billing_email=jasir6#gmail.com&"
"delivery_name=Gx&delivery_address=Yd&delivery_city=Ud&delivery_state=&delivery_zip=Uf&"
"delivery_country=Andorra&delivery_tel=4&merchant_param1=&merchant_param2=&merchant_param3="
"&merchant_param4=&merchant_param5=&vault=N&offer_type=null&offer_code=null&discount_value=0.0&"
"mer_amount=140.0&eci_value=05&card_holder_name=&bank_qsi_no=51000002968&bank_receipt_no=221315916831&"
"merchant_param6=5123450008
</body>
</html>

You can also use this code if you don't want to use plugin to get key-value data
Assign a keyValueMap globally if you want to use it anywhere else
String html = '<html><head></head><body>order_id=1289&tracking_id=111028965908&bank_ref_no=916831&order_status=Success&failure_message=&payment_mode=Credit Card&card_name=MasterCard&status_code=00&"status_message=Approved¤cy=AED&amount=140.0&billing_name=Gx&billing_address=Yd&billing_city=Ud&billing_state=&billing_zip=Uf&billing_country=Andorra&billing_tel=4&billing_email=jasir6#gmail.com&delivery_name=Gx&delivery_address=Yd&delivery_city=Ud&delivery_state=&delivery_zip=Uf&delivery_country=Andorra&delivery_tel=4&merchant_param1=&merchant_param2=&merchant_param3= &merchant_param4=&merchant_param5=&vault=N&offer_type=null&offer_code=null&discount_value=0.0&mer_amount=140.0&eci_value=05&card_holder_name=&bank_qsi_no=51000002968&bank_receipt_no=221315916831&merchant_param6=5123450008</body></html>';
onTap: () {
String temp;
const start = "<body>";
const end = "</body>";
Map<String, dynamic> keyValueMap = {};
if (html.contains(start)) {
final startIndex = html.indexOf(start);
final endIndex = html.indexOf(end, startIndex + start.length);
temp = html.substring(startIndex + start.length, endIndex);
List splitText = temp.split("&");
for (var element in splitText) {
element.runtimeType;
if (element.contains('=')) {
keyValueMap[element.split("=")[0] ?? ""] = element.split("=")[1] ?? "";
}
}
///You'll get all key value in [keyValueMap]
}
},

Use some Html decode plugins. Please go to pub.dev and search flutter_widget_from_html_core, flutter_widget_from_html, html_editor_enhanced,
so many plugins there in pub.dev.

Related

adding elements to json string(array) FLUTTER

I have a JSON string, inside of it I have an array, I want to add data to it as I tried to do it below:
String myJSON = '{"listOfSubtasks":["dasd","dadd","dadsd"]}';
arrayToStringAndBack(addElement) async {
var json = jsonDecode(myJSON);
var getArray = json['listOfSubtasks']; //returns [dasd,dadd,dadsd]
setState(() {
getArray.add(addElement);
});
// as I want to push it to a db I convert [dasd,dadd,dadsd] to a String ["dasd","dadd","dadsd"]
String arrayToString = jsonEncode(getArray);
print(arrayToString);
}
...
textfieldform
- onSaved: (val) {
subtasks = val;
arrayToStringAndBack(val);
},
...
When I type smth and click on a submit button an element is added to the end of an array but once I try to do it one more time, to add an element, the last element that was added changes to one I created.
I want to add as many elements as I want, not just a single one
Solved
var arrayOfSubTasks = [];
arrayToStringAndBack(addElement, arr) async {
var json = jsonDecode(myJSON);
var getArray = json['listOfSubtasks'];
setState(() {
getArray.add(arr);
});
String arrayToString = jsonEncode(getArray);
print(arrayToString);
}
...
onSaved: (val) {
subtasks = val;
setState(() {
arrayOfSubTasks.add(val);
});
arrayToStringAndBack(val, arrayOfSubTasks);
},
You can treat your list of subtasks as a List to be able to add String with List.add(). Then encode the List to a json with jsonEncode()

How do I consume a JSon object that has no headers?

My C# MVC5 Razor page returns a Newtonsoft json link object to my controller (the "1" before \nEdit |" indicates that the checkbox is checked:
"{\"0\": [\"6146\",\"Kimball\",\"Jimmy\",\"General Funny Guy\",\"277\",\"Unite\",\"Jun 2019\",\"\",\"\",\"1\",\"\nEdit |\nDetails\n\n \n\"],\"1\": [\"6147\",\"Hawk\",\"Jack\",\"\",\"547\",\"Painters\",\"Jun 2019\",\"\",\"\",\"on\",\"\nEdit |\nDetails\n\n \n\"]}"
How do I parse this?
I am using a WebGrid to view and I want to allow the users to update only the lines they want (by checking the checkbox for that row), but it doesn't include an id for the 's in the dom. I figured out how to pull the values, but not the fieldname: "Last Name" , value: "Smith"... I only have the value and can't seem to parse it... one of my many failed attempts:
public ActoinResult AttMods(string gridData)
{
dynamic parsedArray = JsonConvert.DeserializeObject(gridData);
foreach (var item in parsedArray)
{
string[] itemvalue = item.Split(delimiterChars);
{
var id = itemvalue[0];
}
}
I finally sorted this one out..If there is a more dynamic answer, please share... I'll give it a few days before I accept my own (admittedly clugy) answer.
if(ModelState.IsValid)
{
try
{
Dictionary <string,string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
foreach (KeyValuePair<string,string[]> keyValue in log)
{
if (keyValue.Value[9] == "1")//Update this row based on the checkbox being checked
{
var AttendeeID = keyValue.Value[0];
int intAttendeeID = 0;
if (int.TryParse(AttendeeID, out intAttendeeID))//Make sure the AttendeeID is valid
{
var LName = keyValue.Value[1];
var FName = keyValue.Value[2];
var Title = keyValue.Value[3];
var kOrgID = keyValue.Value[4];
var Org = keyValue.Value[5];
var City = keyValue.Value[7];
var State = keyValue.Value[8];
var LegalApproval = keyValue.Value[9];
tblAttendee att = db.tblAttendees.Find(Convert.ToInt32(AttendeeID));
att.FName = FName;
att.LName = LName;
att.Title = Title;
att.kOrgID = Convert.ToInt32(kOrgID);
att.Organization = Org;
att.City = City;
att.State = State;
att.LegalApprovedAtt = Convert.ToBoolean(LegalApproval);
}
}
}
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
You can avoid assigning the var's and just populate the att object with the KeyValue.Value[n] value, but you get the idea.

How to properly create an array of JSON objects in Typescript?

I'm trying to create an array of JSON objects in typescript. And following is the approach I have used.
var queryMutations:any = _.uniq(_.map(mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
var item = {facet: "MUTATION", term: mutation.gene + " " + mutation.proteinChange}
return item;
}
else {
return {};
}
}));
var jsonString = JSON.stringify(queryMutations);
is this the correct way to do it? Appreciate your suggestions.
To me it looks ok. I'd personally make a few layout style modifications and use backtick placeholder strings.
var queryMutations:any =
_.uniq(
_.map(
mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
return {facet: "MUTATION",
term: `${mutation.gene} ${mutation.proteinChange}`
} else {
return {};
}
}
)
);
var jsonString = JSON.stringify(queryMutations);

Can we search or filter " data-tag='to-do' " in onenote API ? If yes then how we can do this?

How can we use OneNote tags (like data-tag='to-do') with search or filter in OneNote API. I tried using provide operators but found no success.
I tried in this way --
$url = "https://www.onenote.com/api/v1.0/me/notes";
//$url .= "/pages?search=hello";
$url .= "/pages?filter=data-tag eq 'to-do'";
I want to search data-tag and then extract the data from OneNote pages which contains the data-tag='to-do'.
Any help is appreciated and thanks in advance.
You'll have to run through all your pages.
For each pages, you can retrieve its content with a GET call to https://www.onenote.com/api/v1.0/me/notes/pages/%s/content?includeIds=true
From there you get a string that you can parse.
I'll advise you to use jsoup.
With jsoup you can then write (assuming contentcontains your page's content):
Document doc = Jsoup.parse(content);
Elements todos=doc.select("[data-tag^=\"to-do\"]");
for(Element todo:todos) {
System.out.println(todo.ownText());
}
Sadly OneNote API doesn't support it yet, so I've written my custom parser which extracts notes with data-tags from page content. Here it is:
public class OneNoteParser
{
static public List<Note> ExtractTaggedNotes(string pageContent, string tag = "*")
{
List<Note> allNotes = new List<Note>();
string[] dataTagString = { "data-tag=\""};
string[] dirtyNotes = pageContent.Split(dataTagString, StringSplitOptions.RemoveEmptyEntries);
//First one in this array can be dropped as it doesn't contain todo
for (int i = 1; i < dirtyNotes.Length; i )
{
string curStr = dirtyNotes[i];
Note curNote = new Note();
// Firstly we need to extract all the tags from it (sample html: data-tag="to-do:completed,important" ....)
string allTags = curStr.Substring(0,curStr.IndexOf("\""));
curNote.Tags = new List<string>(allTags.Split(','));
// Now we have to jump to the next ">" symbol and start finding the text after it
curStr = curStr.Substring(curStr.IndexOf(">"));
int depth = 1;
bool addAllowed = false;
for (int j = 0; j < curStr.Length - 1; j )
{
// Finding next tag opener "<" symbol
if (curStr[j] == '<')
{
addAllowed = false;
// Checking if it is not "</" closer
if (curStr[j 1] == '/')
{
// Means this is a tag closer. Decreasing depth
depth--;
}
else
{
// Means this is an tag opener. Increasing depth
depth ;
}
}
else if (curStr[j] == '>')
{
addAllowed = true;
if (j > 0 && curStr[j - 1] == '/')
{
// Means this is a tag closer. Decreasing depth
depth--;
}
}
else
{
if (depth < 1)
{
// Found end of the tag. Saving index and exiting for loop
break;
}
if (addAllowed)
curNote.Text = curStr[j]; // Appending letter to string
}
}
// Filtering by tag and adding to final list
if (tag == "*" || curNote.Tags.Any(str => str.Contains(tag)))//curNote.Tags.Contains(tag, StringComparer.CurrentCultureIgnoreCase))
allNotes.Add(curNote);
}
return allNotes;
}
}
And here is the class Note
public class Note
{
public string Text;
public List<string> Tags;
public Note()
{
Tags = new List<string>();
}
}
To extract todo-s simply call this function:
OneNoteParser.ExtractTaggedNotes(pageContent, "to-do");
Also you can extract other tags like this:
OneNoteParser.ExtractTaggedNotes(pageContent, "important");
OneNoteParser.ExtractTaggedNotes(pageContent, "highlight");
//...

Encompassing object attributes with HTML and return in JSON

currently, i have written the following json search method.
[HttpPost]
public JsonResult Search(string videoTitle)
{
var auth = new Authentication() { Email = "abc#smu.abc", Password = "abc" };
var videoList = server.Search(auth, videoTitle);
String html = "";
foreach(var item in videoList){
var video = (Video)item;
html += "<b>"+video.Title+"</b>";
}
return Json(html, JsonRequestBehavior.AllowGet);
}
On screen, it returns this.
"\u003cb\u003eAge of Conan\u003c/b\u003e"
what should i do? The reason why i want to do this is so that i can make use of CSS to style tags so that it looks aesthetically better as the items drop down from the search input.
thanks
If you want to return pure HTML you shouldn't return JSON, you should rather use the ContentResult:
[HttpPost]
public ContentResult Search(string videoTitle)
{
var auth = new Authentication() { Email = "smu#smu.com", Password = "test" };
var videoList = server.Search(auth, videoTitle);
String html = "";
foreach(var item in videoList)
{
var video = (Video)item;
html += "<b>"+video.Title+"</b>";
}
return Content(html, "text/html");
}
You can request that with standard jQuery.get() and insert directly into DOM.