Stringify single and double quotes - json

With the following code I am creating an object to pass to a webservice. The single quote seems to be handled with a replace in the stringify before the object is passed to the service, but I don't know how to modify the double quote. If I inspect the Program.Comments field it would show the string like \"Word". This will cause an error in the stringify.
Is this an incorrect way to use the stringify for Json
Program = new Object();
Program.Field1 = $('#txtField1').val();
Program.Field2 = $('#ddlField2').val();
Program.Field3 = $('#lblField3').text();
Program.Field4 = $('#ddlField4').val();
Program.Field5 = $('#ddlField5').val();
Program.Field6 = $('#ddlField6').val();
// This field may contain both single and double quotes
Program.Comments = $('#txtComments').val();
Program.Field7 = $('#txtField7').val();
Program.Field8 = $('input[name=chbField8]').is(':checked');
// This will fix the issue of a single quote
vdata = JSON.stringify(Program).replace(/'/g, "\\'");d

Related

decrypt str in dictionary using bytes and fernet

I am trying to decrypt encrypted strs that are inside of a dictionary. To do this, the values must first be encoded, then the data can be decrypted and then decoded. I am struggling to encode the values without encoding the keys.
P.S: here is the printout for line 4:
b'{"pid": 6, "parent_first": "gAAAAABjAsAWbyxBsR804rVdMJ_Dzfj1s5s9GYVFSB2AJq3VSHTjH2V7lE4lt2gtO3LrhL6eKTm1qx153VO-g5xxWRb6mjXqvQ==", "parent_last": "gAAAAABjAsAWgiUupGo06d-tLY3WHgpfu5g0y55DjCPXdx4G2hIkEw50e3HAyi_r6z5NBHnJkevR8WkAy-2mhjvhUFRUk7Le8Q==", "email": "gAAAAABjAsAWAOTCver2_4bsBfrDA8SIdrykIH8Jojkd5100HT9y2Yz6ZnbZfYBqOYgwcKEquFhRGRZtey0A1Mdu12GxSHD3OdN8zb1DlLF0cP6O9tZEHGc=", "password": "f58a1612e9af7b5ee7e2141730f9a680f94765ad082918d489be42bde5d9ab23", "username": "9e7bd6851718b496e3c9cb0db480cbb8b87cf0455a7d627658906158357849b1"}'
for user in query:
dict = user.to_dict()
res_bytes = json.dumps(dict).encode('utf-8')
print(res_bytes)
res_bytes['parent_first'] = decrypt(res_bytes['parent_first'.encode('utf-8')])
res_bytes['parent_last'] = decrypt(res_bytes['parent_last'.encode('utf-8')])
res_bytes['email'] = decrypt(res_bytes['email'.encode('utf-8')])
res_bytes['username'] = decrypt(res_bytes['username'.encode('utf-8')])
dict = json.loads(res_bytes)
print(dict)
this gives an error of byte indices must be integers or slices, not bytes
res_bytes contains a byte sequence, so trying to work with it as if it's a dictionary instance doesn't make sense and results in the error you're seeing.
Basically, there's no reason to use json.dumps() and json.loads() in this code snippet.
Instead, try something like:
for user in query:
u = user.to_dict()
u['parent_first'] = decrypt(u['parent_first'])
u['parent_last'] = decrypt(u['parent_last'])
u['email'] = decrypt(u['email'])
u['username'] = decrypt(u['username'])
print(u)
A few notes:
Once you've converted user to a dictionary, proceed to use it as a dictionary.
Fernet.decrypt() can take either a str or bytes as input, so no need to worry about encoding/decoding it.

Why is "Input string was not in a correct format." in the query in mySQL?

In the following code,
I get a run time error of
"Input string was not in a correct format." after oCommand.ExecuteReader().
oCommand.CommandText = "CheckOutItem";
oCommand.CommandType = System.Data.CommandType.StoredProcedure;
oCommand.Parameters.AddWithValue("#OrderID", OrderID);
oCommand.Parameters.AddWithValue("#GivenLargeSizeName", Enum.GetName(typeof(Size), Size.REGULAR));
oCommand.Parameters.AddWithValue("#GivenSmallSizeName", Enum.GetName(typeof(Size), Size.SMALL));
oCommand.Parameters.AddWithValue("#Latitude",oOrder.OrderTimeLocation.Location.latitude);
oCommand.Parameters.AddWithValue("#Longitude",oOrder.OrderTimeLocation.Location.longitude);
oCommand.Parameters.AddWithValue("#ListingID", MySqlDbType.Int64);
oCommand.Parameters.AddWithValue("#Quantity", MySqlDbType.Int16);
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
foreach (var OrderItem in oOrder.OrderItems)
{
oCommand.Parameters["#ListingID"].Value = OrderItem.ListingID;
oCommand.Parameters["#Quantity"].Value = OrderItem.Quantity;
oCommand.Parameters["#Size"].Value = Enum.GetName(typeof(Size), OrderItem.Size);
oCommand.Parameters["#DeliveryMethod"].Value = Enum.GetName(typeof(DeliverMethod), OrderItem.DeliveryPickupMethod);
using (var reader = oCommand.ExecuteReader())
{
while (reader.Read())
{
Int64 OrderItemID = Convert.ToInt64(reader["#ORDER_ITEM_ID"]);
Int64 OrderItemStatusID = Convert.ToInt64(reader["#ORDER_ITEM_STATUS_ID"]);
Int64 OrderItemPriceID = Convert.ToInt64(reader["#ORDER_ITEM_PRICE_ID"]);
TotalOrderCostFromDB = TotalOrderCostFromDB + Convert.ToDecimal(reader["#TOTAL_ORDER_COST"]);
}
}
}
if I use statements like
oCommand.Parameters.AddWithValue("#ListingID",OrderItem.ListingID)
works fine but I can not loop.
All the values I am assigning are correct in debugging and no nulls or weird stuff getting into .Value.
Since I get the correct answer in AddWithValue method, I don't think I have any issue with StoredPoocedure.
Is there a better approach to loop for this purpose?
After some debugging, I was able to narrow down the issues to last two lines
oCommand.Parameters.AddWithValue("#Size", MySqlDbType.VarChar);
oCommand.Parameters.AddWithValue("#DeliveryMethod", MySqlDbType.VarChar);
If I initialize this with a dummy string, everything is fine. But initializing with VarChar or String cause problems.
For my understanding, following returns a string right?
Enum.GetName(typeof(Size), OrderItem.Size)

How to get the value of a JSON element in node js? Unable to parse the value in below code

Below is the theJson string which I have converted to object by JSON.parse
var clientScopeJson={"cl1":{"List":"rwe","urlList":["nclsdlc","alkdcjla"]}};
JSON.hasOwnProperty(id) returns as true but JSON.id gives undefined:
id = "cl1"
//scope = JSON.parse(clientScopeJson);
console.log(clientScopeJson);
clientId = "cl1";
exists = clientScopeJson.hasOwnProperty(clientId); // This returns as true
console.log(exists);
scopeList = clientScopeJson.clientId;
console.log(scopeList);
If you want to access key that is saved in variable, you can access it like this
const clientId = "cl1";
const scopeList = clientScopeJson[clientId];
If you try to use it with dot, you are trying to access 'clientId' key.

AS3 Custom string formula parser

My goal is to create some kind of Parser to parse string formulas, similar to Excel formulas.
Formula string example (barcode example) -
"CONCAT('98', ZEROFILL([productNumber],5,'0'), ZEROFILL(EQUATION([weightKG]*1000),5,'0'))"
where
'98' - String
[productNumber] and [weightKG] - are variables that can be changed
CONCAT, ZEROFILL and EQUATION are methods which exist in class
For this formula with variables [productNumber] = '1' and [weightKG] = 0.1 result must be
'980000100100'
The question is how to split/parse whole string to parts and detect methods, variables and string values?
Another idea occurred, while i was typing - is to store whole formula in XML format.
Thank You.
You can use String.split() to get an array of substrings.
However, using your example, calling split(",") would give you the following array:
[0]=CONCAT('98'
[1]= ZEROFILL([productNumber]
[2]=5
[3]='0')
[4]= ZEROFILL(EQUATION([weightKG]*1000)
[5]=5
[6]='0'))
That doesn't seem like it will be very helpful for your project. Instead, you might think about creating a parse() function with some logic to find useful substrings:
function parse(input:String):Array {
var firstParen:int = input.indexOf("(");
var lastParen:int = input.lastIndexOf(")");
var formulaName:String = input.substring(0, firstParen);
var arguments:String = input.substring(firstParen, lastParen);
var argumentList:Array = parseArgs(arguments);
var result:Array = new Array();
result.push(formulaName);
//Recursively call parse() on the argumentList
foreach (var elem:* in argumentList) {
result.push(elem); //Could be string or array.
}
}
function parseArgs(input:String):Array {
// Look for commas that aren't enclosed inside parenthesis and
// construct an array of substrings based on that.
//A regex may be helpful here, but the implementation is left
//as an exercise for the reader.
}

How to make a path with a String name into a simple String

How do i make the path of the item and its name that is given within the "" into a simple string
what i mean is:
when i just do this
var myText:String = new String("pathToImage")
trace(myText)
in the outPut window I get this : pathToImage.And that is Ok
But can i put double quotes into a string, like this
var myText:String = new String(" pathToImage("ImageName") ")
trace(myText)
and in the outPut window to get this : pathToImage("ImageName")
cause I'm trying this way, but it givems me an error:
1084: Syntax error: expecting rightparen before ImageName.
So is there a way of doing this?
First of all, it’s enough if you just use string literals. You do not need to call the String constructor:
var myText:String = "pathToImage";
Second, string literals are either quoted with double quotes " or single quotes '. If you want the quotation character itself as a part of the string, you need to escape it using the escape character \. So if you want to have a string pathToImage("ImageName"), then you will have to do it like this:
var myText:String = "pathToImage(\"ImageName\")";
Alternatively, you can also use single quotes here. Using single quotes as the string delimiter allows you to use double quotes within the string without having to escape them. The same applies to single quotes within double-enquoted strings:
var myText:String = 'pathToImage("ImageName")';