Turn a python windows path into a regular path for JSON - javascript

I want to turn \\\\Network Share\\Folder\\Folder\\File.jpg into a regular path - \\Network Share\Folder\Folder\File.jpg - for a JSON string that I am passing to JavaScript. My code is:
def searchFile(fileName):
for entry in os.scandir(folderToSearch):
if fileName.upper() in entry.path.upper():
if entry.is_file():
return entry.path
Which is returning with the extra backslashes. When I read the JSON data in JavaScript, it cannot find the file due to the extra backslashes. How do I transfer the data from Python to JavaScript?
I am using the eel library.
EDIT
This is how I am creating my JSON data to pass to JavaScript:
def createUserJSON():
UserData = {}
JSONData = []
UserData['fullName'] = "Test User"
UserData['email'] = "Test.User#test.com"
UserData['userImage'] = searchFile("TestUser")
json_data = json.dumps(UserData)
JSONData.append(json_data)
return JSONData
This then returns:
['{"fullName": "Test User", "email": "Test.User#test.com", "userImage": "\\\\Network Share\\Folder\\Folder\\File.jpg"}']

Related

How do I set JSON data as a cookie while preserving the indentation?

I'm trying to set a cookie containing some JSON data, but I also need to preserve line breaks. I've got a way of keeping them and rendering them which works fine in the console but when I actually put the code in a tag, it doesn't work.
Here's the code:
actualData = JSON.stringify(data.replaceAll("\n", "|")).replaceAll("\\", "");
document.cookie = `data=${actualData}; path=/;`;
Here's the expected input and output, which is in the console:
//input = '[\n {"content": [\n {"title": "e"}\n ]}\n]'
//output = 'data="[| {"content": [| {"title": "e"}| ]}|]"; path=/;'
Here's the input and output when run from a <script> tag:
//input = '[\n {"content": [\n {"title": "e"}\n ]}\n]'
//output = 'data="[\\n {\\"co|te|t\\": [\\n {\\"title\\": \\"e\\"}\\n ]}\\n]"'
I don't understand how the same code is returning a completely different result. I don't know how it gets even worse when flask handles it:
[n {"content": [n {"title": "e"}n ]}n]
Is it something to do with how cookies are handled? Is it something to do with how I'm outputting it?
you can change your tactic and format the JSON to a string (with the required indentation), then base64 encode the string, store the produced value to the cookie. Then when you receive back the cookie in a subsequent request, you can base64 decode it.
Full example below:
import json
import base64
my_dict = {
"id": "12345",
"name": "myname",
"text": "",
"list_field": [
123,
456,
"some string"
]
}
my_string = json.dumps(my_dict, indent=4)
print(my_string)
my_string_bytes = my_string.encode('ascii')
b64_encoded = base64.b64encode(my_string_bytes)
print(b64_encoded)
b64_decoded = base64.b64decode(b64_encoded)
my_string_decoded = b64_decoded.decode('ascii')
print(my_string_decoded)
if my_string == my_string_decoded:
print("initial and decoded strings match!")
much cleaner approach, and not prone to unintentional character replacements

How to apply regular expression for Javascript

I am trying to get message log from Azure application Insight like this
az monitor app-insights --app [app id] --analystics-query [condition like specific message id]
Then I got a message like this
"message": [
"Receiving message: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller":null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"format version","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp":null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{"sys":"otel","msg":"Testing Centralized Event Publisher with App1 (using logback)","app":{"name":"otel","service":"postHouse","status":"status name","method":"POST","protocol":"HTTP","resp_time_ms":"250","status_code":"4"},}}"
] }
So that I would like to apply Regular Expression for this message to get only the message from {"type.....to "status_code":"4"},}} and also convert it to JSON format
I have code like this in my .js file
Then('extract json from {string}', function(message){
message = getVal(message, this);
const getmess = message.match(/{(.*)}/g);
const messJson = JSON.parse(getmess);
console.log(messJson);
})
But it doesn't work for me
SyntaxError: Unexpected token \ in JSON at position 1
How can I apply this in my code on Javascript? Thank you so much for your help
Try this. But keep in mind, that current regex is binded with provided program output syntax. If output will be different in wrapper structure, this regex might not work any more.
// Text from app
const STDOUT = `
"message": [ "Receiving message: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller":null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"format version","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp":null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{"sys":"otel","msg":"Testing Centralized Event Publisher with App1 (using logback)","app":{"name":"otel","service":"postHouse","status":"status name","method":"POST","protocol":"HTTP","resp_time_ms":"250","status_code":"4"},}}"
] }
`;
// Match JSON part string
let JSONstr = /.*\[\s*\"Receiving message:\s*(.*?)\s*\"\s*]\s*}\s*$/.exec(STDOUT)[1];
// Remove trailing comma(s)
JSONstr = JSONstr.replace(/^(.*\")([^\"]+)$/, (s, m1, m2) => `${m1}${m2.replace(/\,/, "")}`);
// Convert to object
const JSONobj = JSON.parse(JSONstr);
// Result
console.log(JSONobj);
Try this one:
/.*?({"type":.*?,"status_code":"\d+"\})/
When used in Javascript, the part covered by the parentheses counts as Group 1, i.e.,:
const messJson = JSON.parse(message.match(/.*?({"type":.*?,"status_code":"\d+"\})/)[1]);
Reference here: https://regexr.com/66mf2

Convert object to JSON in serverside JavaScript aspx

My application uses serverside JavaScript in aspx files on IIS 8 (Windows 2012R2) .
I want to convert a javascript hash to JSON.
My file test.aspx:
<%#language="javascript" Debug="true"%>
<%
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var header =
{
"typ": "JWT",
"alg": "HS256"
};
var str = serializer.Serialize(header);
Response.Write(str);
%>
Result: ["typ","alg"]
Expected result: {"typ":"JWT","alg":"HS256"}
Why does the JavaScriptSerializer not work as expected?
I'm not sure how well System.Web.Script.Serialization.JavascriptSerializer, which is a server component, will work inside client code.
Probably you'll have better results just using
var str = JSON.stringify(header);
instead of
var str = serializer.Serialize(header);

undefined key after parse the string form json.dumps() in python by JSON.parse()

I have a string returned from python by json.dumps(). I am using python 2.6 or 2.7. When I parse it using JSON.parse() in JavaScript. I got undefined with keys.
My string recieved by javascript(ajax) is looks like:
{'country': u'\u4e0a', 'Search': {'city_num': 25, 'index': ''}, 'Locc': ['116.116', '29.29'], 'cid': '285'}
When I use:
objstr = JSON.parse(jsonstr);
alert(objstr.country);
I got undefined in popup alert window.objstr[0].country and objstr[0]['country'] got undefined either.
What should I do? I have read several article on stackoverflow and google and I still confused about how to solve this problem. Any one can give me some advices? Thanks.
Edit
My codes to receive request from ajax:
def POST(self):
resultline = {}
file = open("..\\cache\\res.cache", 'r')
last_pos = self.get_pos()
print last_pos
pos = int(last_pos)
file.seek(pos)
line = file.readline()
print line
if ''== line:
file.seek(0, 0)
line = file.readline()
last_pos = file.tell()
self.store_pos(last_pos)
resultline = line
file.close()
if '' != resultline:
resultlinetmp = resultline[0:len(resultline)-1]
return json.dumps(resultlinetmp)

how to get Hmac code with javascript

I can get a hmac sing using Python as following:
import hmac, base64, hashlib
def make_sign():
hash_data = "data"
secret = "this is secret"
sha512 = hashlib.sha512
hmac_obj = hmac.new(secret, hash_data, sha512)
str_hash = hmac_obj.digest()
sign = base64.b64encode(str_hash)
hex_hash = hmac_obj.hexdigest()
hex_sign = base64.b64encode(hex_hash)
print "correct_sign:",sign
print "hex_digest_sign:",hex_sign
make_sign()
output:
correct_sign: Lg4pXNCIpitNQt2DLU19qWb+FxdsYZlK4LLncfkTzSidrYoFJLNolUziRqh09B5HyRdCTEP7enZp6/Te34FK1g==
hex_digest_sign: MmUwZTI5NWNkMDg4YTYyYjRkNDJkZDgzMmQ0ZDdkYTk2NmZlMTcxNzZjNjE5OTRhZTBiMmU3NzFmOTEzY2QyODlkYWQ4YTA1MjRiMzY4OTU0Y2UyNDZhODc0ZjQxZTQ3YzkxNzQyNGM0M2ZiN2E3NjY5ZWJmNGRlZGY4MTRhZDY=
but with js, I can get hex_digest_sign, but I need to get correct_sign for web request.
function make_request() {
hash_data = "data"
secret = "this is secret"
hmac = hmac_512(hash_data, secret)
var sign = $.base64.encode(hmac),
console.log("js_sign="+sign);
}
function hmac_512(message, secret) {
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA512, secret);
hmac.update(message);
var hash = hmac.finalize();
return hash;
}
js output:
js_sign="MmUwZTI5NWNkMDg4YTYyYjRkNDJkZDgzMmQ0ZDdkYTk2NmZlMTcxNzZjNjE5OTRhZTBiMmU3NzFmOTEzY2QyODlkYWQ4YTA1MjRiMzY4OTU0Y2UyNDZhODc0ZjQxZTQ3YzkxNzQyNGM0M2ZiN2E3NjY5ZWJmNGRlZGY4MTRhZDY="
the correct sign is correct_sign: Lg4pXNCIpitNQt2DLU19qWb+FxdsYZlK4LLncfkTzSidrYoFJLNolUziRqh09B5HyRdCTEP7enZp6/Te34FK1g==
how to get it in js?
I suspect that you are running into trouble with types and encoding. According to the CryptoJS source, the iterative hashing style that you are using returns a WordArray once you call finalize().
With that, once you go to print the results, you are printing the contents of the WordArray.
The purpose for itterative hashing is typically if you have a large input, you can break it into chunks to work on one piece at a time. Try the below edit I made that removes this as it does not look like you need to iterate.
function hmac_512(message, secret) {
var newHMAC = CryptoJS.HmacSHA256(message, secret);
return newHMAC;
}
The above will simply return the HMAC in string form which, once Base64 encoded, should match the result you see in Python.
Hope this helps!

Categories