Flutter access session as Json array - json

i have added a json array in session. when i try to access the array, it shows as string. that is without any double quotes. but i want it as json array. Am i missing anything here ? please help.
this is the array :
var login_data = {"success":1, "user":{"id":"13","firstname":"Reda","lastname":"Estyu"},"shop_name" :"Market"}
await FlutterSession().set('session_data', login_data);
var get_data = await FlutterSession().get("session_data");
print(get_data);
after accessing it from session it looks like this :
{success:1, user:{id:13,firstname:Reda,lastname:Estyu},shop_name :Market}

Setting Map returns Map and setting String returns String - makes sense. Encode Map to String before setting.
await FlutterSession().set('session_data', jsonEncode(login_data));
...
var get_data = jsonDecode(await FlutterSession().get("session_data"));

Related

Is it possible to iterate over a json object having `\n` and \`` characters in typescript?

I have a json object which is something like below:
"\"{\\n \\\"Foo\\\" : \\\"1234\\\",\\n}\""
Is it somehow possible to iterate through this json object?I tried but my logic did not work which i feel is basically because of these \n and \ i am unable to iterate.How can i get rid of these unnecessary characters ?
The string you've shown is double-encoded JSON if we assume that you've removed some of the content (it has a trailing , in the JSON, which JSON doesn't allow).
If you run it through JSON.parse, you get a string containing JSON for an object.
If you run that through JSON.parse, you get an object.
E.g.:
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
Then you loop through that object's properties in the normal way (for-in, Object.keys, Object.entries, etc.).
Live Example:
const str = "\"{\\n \\\"Foo\\\" : \\\"1234\\\"\\n}\"";
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
for (const key in obj) {
console.log(`${key} = ${obj[key]}`);
}
That code is also valid TypeScript (playground link), though if you have a type you can apply to obj so it doesn't default to any, that would be good. (You could apply {[key: string]: any} to it at minimum.)

parsed data can't save to mysql

the json data is
"{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...
I'm replacing the symbol by
var results = post
.replace(/\{/g, '[[')
.replace(/\"/g, '\'')
.replace(/\,/g, '\'],[')
.replace(/\:/g, ',\'')
.replace(/\}/g, '\']]')
.replace(/\\([^u])/g, '$1')
;
console.log(results); shows
[['n925D','1'],['t925D','23.5'],['h925D','3276.8'],...
console.log(query.sql); shows
INSERT INTO table (did,val) SET '[[\'n925D\',\'1\'],[\'t925D\',\'23.5\'],[\'h925D\',\'3276.8\'],
how can I remove the \ actually...
You can't reliably parse JSON (or XML or HTML) with regexes. Instead, parse it, change the data, and re-emit it.
var jsonData = '{\"n925D\":1,\"t925D\":23.5,\"h925D\":3276.8,...';
// Parse it into a hash
var jsonParsed = JSON.parse(jsonData);
// Change the hash in jsonParsed to an array of arrays.
// Convert it back into JSON
jsonData = JSON.stringify(jsonObj);

Webapi return json with extra double slashes for a path property

I am using asp.net webapi and returning json response. One of the property in the json response has got a path field. When i check in Console.WriteLine i get the values without additional double slashes. But the json response in postman contains extra double slashes.
Expected:
\\test.com\cax\mef\160704\160704Z003.abc
But in the json response the output i am getting is:
"path": "\\\\test.com\\cax\\mef\\160704\\160704Z004.abc"
And my json settings in webapi.config:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Can anyone help me what is the problem and how to solve this?
Why i am getting extra double slashes?
Thanks
The added slashes are their as Escape characters.
This Could be caused when you asign the URL to the Variable before you return the response via the Webapi. Eg:
xObj.path = urlPath;
----------------
xObj.path = urlPath.ToString();
It All Depends on where and how you Assigned them.. If they are coming for a Database they could have also Been Stored Like that.
it could also just be the IDE showing it to you Like that. This Often Just Adds the Escape characters to the interpretation of the value.. but when the value is used they are no longer present.
this is how you parse the JSON
var jsonResponse = '{ "firstName":"John" , "lastName":"Doe", "path" : "/test/test/adasdasd.com" }';
var obj = JSON.parse(jsonResponse);
console.log(obj);
You Will note that my Example doesn't have the double slashes. That is because if you use the response directly it wont have any either.

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

trying to convert data from Domino Access Service to a JSON string via JSON.stringify

I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John