General node.js data to mysql with stringify & escape - mysql

I need a better understanding about stringify, escape and storing in mysql database. The task looked easy but with escaping I run into some trouble. So I would be happy for general explanation of the following questions:
What I try is to store a javascript object in a mysql DB. It works fine with stringify prior to send. Getting it back from the DB just parse it and everything is fine.
let myObj = {
name: 'Paul',
age: '24'
}
Now, I have additionally a message in my object, which can have special characters:
let myObj = {
name: 'Paul',
age: '24',
message: 'message with special characters: ',`´"~'
}
Also no problem, I started to escape. The result:
let myObj = {
name: 'Paul',
age: '24',
message: 'message with special characters: \'\,\`´\"\~'
}
If I do stringify the object, I get following result:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \\'\\,\\`´\\\"\\~"
}
Sending it to mysql DB gives following error:
(node:13077) UnhandledPromiseRejectionWarning: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '\,\`´\"\~"}
Due to the error I manipulated the special characters and removed the additional '\' which gives following result:
obj.message = obj.message(/\\\\/g,'\\');
output:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \'\,\`´\\"\~"
}
everything is fine and the data is transfered to the DB and my mysql update query has no failure anymore.
Questions:
Is there a better way dealing with escaping inside an object, which will be stringified and send to a mysql DB?
If yes, how is it done? Or is there no other way as to remove the additional backslashes inserted due to the stringify?
One step further. The message has included a new line: \n:
output stringified:
{
"name": "Paul",
"age": "24",
"message": "message with special characters: \'\,\`´\n\\"\~"
}
Sending it to the DB I get following entry (Where \n: I get a new line):
{"name":"Paul","age":"24","message":"message with special characters: ',`´
\"~"}
Which results in an error parsing it back. here is the log (serverside) prior parsing (error makes sense):
{"name":"Paul","age":"24","message":"\',`´\n' +
'\\"~"}
Question:
Regarding the upper part, what do I have to do, to get the \n also escaped? Which means, that the DB entry is correct and the DB doesn't take the \n to start a new line?
Happy for any explaning / help!

I don't know how's the correct way or the easy way, but that's how I did it when I needed to insert a user generated field as a JSON in a MYSQL database
string_cleanJSON_preStringify(str)
{
if(!str.replace) return str;
str=str.replace(/'/g,"\\'"); //escape all at least ' once
str=str.replace(/"/g,'\\"'); //escape all at least " once
str=str.replace(/[\t\r\n\f]/g,''); // remove problematic escape characters
if(str.charAt(str.length-1) == '\\') str+=' '; // add blank space at the end if \ is last character - for example: {"var":"\"} would be problematic
return str;
}
string_cleanJSON_to_query(str)
{
str = str.replace(/(\\)+\\/g,'\\'); // replace all \ more than 1 in a row, to be just 1 ( \\ -> gets escaped again when it's processed to just \)
str = str.replace(/(\\)+"/g,'\\\\\\"'); // replace all \" more than 1 (ex \\\") - i don't know why \\\\\\ - this seem to work in my case, might need to alter based on str manipulations before insert
str = str.replace(/(\\)+'/g,"\\'"); // i don't know why \\ - this seem to work in my case, might need to alter based on str manipulations before insert
str = str.replace(/(\\)+t/g,"t"); // same process as above but with problematic escape characters
str = str.replace(/(\\)+r/g,"r");
str = str.replace(/(\\)+n/g,"n");
str = str.replace(/(\\)+f/g,"f");
return str;
}
How I use this to get a query:
let o = {field_data:string_cleanJSON_preStringify(user_gen_field_data)}
let j = string_cleanJSON_to_query(JSON.stringify(o));
let q = `INSERT INTO blabla (json) VALUES('${j}')`;

Related

python RegEx json Double quotes

I got a json through the spider, but the json format has a problem, name:value, the name is missing double quotes. like this:
{ listInfo:[{title:'it is title',url:'http://test.com',imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}
I want add double quotes in "name",and need to exclude String of [http { ...]
{ "listInfo":[{"title":'it is "title"',"url":'http://test.com',...
I tryed this but it is not work
#(.*?)\:(.*?)\n'
pattern = re.compile(r'^((?![http]\").)*\:(.*?)\n', re.MULTILINE )
content = content.replace(pattern.search(content).group(1),'\"'+pattern.search(content).group(1).strip()+'\"')
I also tryed
How to add double quotes to the dictionary?
content = '''
{ listInfo:[{title:'it is title',url:'http://test.com',
imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',
pubtime:'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',
imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}
'''
# dict_str = lambda data : re.sub(r'(\w+):\s*(-?\d[\d/.]*)',r'"\1": "\2"',data)
dict_str = lambda data : re.sub(r'(\w+):(.*?)\n',r'"\1": "\2"',data)
for i in [content] :
var1=dict_str(i)
print(var1)
the result is look like:
{ "listInfo": "[{title:'it is title',url:'http://test.com',""imgurl": "'http://test.com',imgurl2:'',abstract:'',source:'',""pubtime": "'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',""imgurl": "'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}"
Who knows how to write regEx.
Thinks!
I used a comparative method to solve it.
script = script.replace('abstract','\"abstract\"')
...
:(

How to return number and newline with JSON

I want to return a number and a new line
{ data : "3
"}
But every time, I try to do this it is considered invalid
Update
My parser tool tries to do things with Newlines. Here is the complete screenshot:
** Update 2**
This is with jsonlint.com
The problem is that data is not a valid key (check https://www.json.org/ or Do the JSON keys have to be surrounded by quotes?), you need to use quotes for keys in order to have valid syntax. Also you need to add \n for a new line character:
{ "data": "3\n"}
I pasted this into the console without an error:
{ "data" : "3\n"}
Testing one step further:
a = { "data" : "3\n"}
a.data + "hello" // pasted into the console
produced this:
3
hello

Python: create json query

I'm trying to get python to create a json formatted like :
[
{
"machine_working": true
},
{
"MachineName": "TBL165-169",
"MachineType": "Rig Test"
}
]
However, i can seam to do it, this is the code i have currently but its giving me error
this_is_a_dict_too=[]
this_is_a_dict_too = dict(State="on",dict(MachineType="machinetype1",MachineName="MachineType2"))
File "c:\printjson.py", line 40
this_is_a_dict_too = dict(Statedsf="test",dict(MachineType="Rig Test",MachineName="TBL165-169")) SyntaxError: non-keyword arg after
keyword arg
this_is_a_dict_too = [dict(machine_working=True),dict(MachineType="machinetype1",MachineName="MachineType2")]
print(this_is_a_dict_too)
You are trying to make dictionary in dictionary, the error message say that you try to add element without name (corresponding key)
dict(a='b', b=dict(state='on'))
will work, but
dict(a='b', dict(state='on'))
won't.
The thing that you presented is list, so you can use
list((dict(a='b'), dict(b='a')))
Note that example above use two dictionaries packed into tuple.
or
[ dict(a='b'), dict(b='a') ]

Error parsing SQL Query in JSON

I'm using a JSON file to store some SQL queries as key value pairs but am getting parse errors which i think is being caused by some of the SQL Query characters.
If i remove the SQL query and enter plain text it parses fine so its definitely some SQL character thats causing the parse error.
Small snippet below
{
"SqlPart1": {
"SqlRead": "
SELECT
Date,
ID
FROM DB.dbo.TableName
WHERE SendEmail = 'true'
",
"SqlWrite": "SqlQuery"
},
"SqlPart2": {
"SqlRead": "SqlQuery",
"SqlWrite": "SqlQuery"
}
}
Error: Parse error on line 3: ...": { "SqlRead": " SELECT Date, ----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
any idea's whats causing the issue?
I tried escaping the single quotes in the WHERE clause but made no difference.
thanks
JSON doesn't support multi-line text data in this way. You have to do it this way:
{
"SqlPart1": {
"SqlRead": "\n SELECT\n Date, ...."
...
I.e. there must be no line breaks in string literals.
if you need to keep the formatting say for example in a big sql query, you can split
{
"SqlPart1": {
"SqlRead": ["SELECT",
"Date,",
"ID",
"FROM DB.dbo.TableName",
"WHERE SendEmail = 'true'"]
",
"SqlWrite": "SqlQuery"
},
then join the array into a single string in your code. Not ideal but it's a limitation of json\javascript.

How to send multiple documents using RMongo

I am following the conventions from http://docs.mongodb.org/manual/reference/method/db.collection.insert/
to send a batch of multiple documents in one call of RMongo::dbInsertDocument.
data=data.frame(A=c(1,2),B=c(3,4))
L=lapply(split(data,rownames(data)),as.list)
names(L)=NULL
dataJSON = toJSON(L)
cat(dataJSON)
which gives the following result:
[
{
"A":1,
"B":3
},
{
"A":2,
"B":4
}
]
Then
dbInsertDocument(rmongo.object=myRmongo.object, collection=myCollection, doc=dataJSON)
returns the following error:
Error in ls(envir = envir, all.names = private) :
invalid 'envir' argument
Note that if I replace
L = L[[1]
Then
cat(dataJSON)
gives the following result:
{
"A":1,
"B":3
}
and the same call to dbInsertDocument works with no error (and the data is indeed sent to the database)
Has anyone figured this out? I would really like a better way to do this, but for now am just looping over the list (not ideal)
data=data.frame(A=c(1,2),B=c(3,4))
L=lapply(split(data,rownames(data)),as.list)
names(L)=NULL
for (i in 1:NROW(L)) {
dataJSON = toJSON(L[[i]])
output <- dbInsertDocument(mongo, "test_data7", dataJSON)
}