How to insert JSON string to mysql with node.js script? - javascript

I have a string like this:
{
WABrowserId: '"hTCl7asDPe/EIymrQC57Hg=="',
WASecretBundle: '{"key":"o65mhfj8XZpuCIIgamAdsaibobs0HKiiBCwTAn36qms=","encKey":"nw5vM2sa05Eh94boiPO5r2qi5fS7CZmJwNNWgIsEj08=","macKey":"o65mhfj8XZpuCIIgamAd3Eibobs0HKiiBCwTAn36qms="}',
WAToken1: '"ArRasrW9r63ByrbKDAauchBnzEUYOO9q0HTWJYfG0RM="',
WAToken2: '"1#GGZtYQss1DkFVbXvuH28Dmm6YdI6wkHvqN1lSbAVAj+S4N5g3qQwuEAdQBsEp/j1cPVRu4bMexECrQ=="'
}
I got an error message like this:
UnhandledPromiseRejectionWarning: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WABrowserId = '"hTCl7AYDPe/EIymrQC57Hg=="', WASecretBundle = '{"key":"o' at line 1
How can I insert this string into a MySQL database with a Node.js script?

You can't insert normal JS object, you need to parse into JSON using JSON.stringify(obj) function then insert into the database.
you might also need to remove the single quotes and use double quotes.

Related

Receiving undefined when trying to use FOR JSON in MSSQL and trying to read the root key

I am trying to use a JSON result from MSSQL npm package and a Azure Database the results are in JSON but when i have tried to use bracket or dot notation it returns undefined.
this is what it returns and i am trying to access the personalNames node
[ { 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B':
'{"personalNames":[{"id":"H0AK00014","name":"WHITTAKER RICHARD"}} ]
req.query("SELECT TOP 3 CAND_ID AS id, REPLACE(CAND_NAME, '\"', '') AS name FROM [dbo].[Merge_FEC_80_18] FOR JSON PATH, ROOT('personalNames')")
.then(function (recordset) {
console.log(recordset.recordset[0].personalNames);
I the JSON this returns is only this part:
{"personalNames":[{"id":"H0AK00014", . . .
That JSON document is returned to the client in single-column resultset. So you need to get the string value from the first row of the resultset, and that's your JSON.

Cannot create stored procedure with sequelize

I am running the following SQL query:
Executing (default): DROP PROCEDURE IF EXISTS x;
DELIMITER $$
CREATE PROCEDURE x()
BEGIN
# do something
END $$
DELIMITER; $$
Like so:
sequelize.query(query, {
type: sequelize.QueryTypes.SELECT
});
But I get this error (even though it works just fine, if I use any other SQL client):
SequelizeDatabaseError:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'DELIMITER $$
CREATE PROCEDURE x()
BEGIN
I already added multipleStatements = true to my connection config, but it does not do anything.
Update
I ended up using RAW instead, like so:
sequelize.query(query, {
type: sequelize.QueryTypes.RAW
});
DELIMITER is not part of MySQL server, it's part of the MySQL command line client. This feature is not available in the driver.
Source: https://github.com/mysqljs/mysql/issues/280#issuecomment-8081626
Your error is actually in the last line. Take out the $$ after DELIMITER;
The statement: DELIMITER; resets the delimiter to ; the $$ after that confuses the syntax analyzer.

Read JSON String Shown In URL Using Javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

Perl's JSON decode_json with JSON.stringify string

I have a front-end and back-end script that are working with one another. The front-end script of type JS does JSON.stringify on an array of strings and calls the backend script for validation on this string.
The backend script of type Perl grabs this string and does a decode_json from the Perl module JSON. At this point the Perl script is croaking.
I think the problem has to do with what's returned by JSON.stringify.
JS:
var jl = ["Flash", "WonderWoman", "BatMan", "SuperMan", "GreenLantern", "MartianManHunter", "HawkWoman"];
var $jl_string = JSON.stringify(jl);
// assume there is code here that makes an AJAX call which calls the backend script
Returns this:
"[\"Flash\", \"WonderWoman\", \"BatMan\", \"SuperMan\", \"GreenLantern\", \"MartianManHunter\", \"HawkWoman\"]"
Perl function that validates the above stringified string:
sub are_jl_members {
my ($jl_string) = #_;
print "<p>$jl_string</p>";
# Failing here. Why?
my $jl = decode_json $jl_string;
print Dumper([$jl]);
}
Thanks for the help.
The problem is the extra "\" in your $jl_string. Your JSON.stringify call is correct satanically.
How are you printing $jl_string here?
Returns this:
"[\"Flash\", \"WonderWoman\", \"BatMan\", \"SuperMan\", \"GreenLantern\", \"MartianManHunter\", \"HawkWoman\"]"

Result of BsonDocument.ToJson fails when used in JSON.parse

I'm retrieving data from MongoDB and then sending it to client:
var bsonDocument = ... retrieve from database ...
var dto = new Dto { MyBson = bsonDocument.ToJson() };
On the client I'm trying to parse MyBson property using JSON.parse.
I'm getting the following error: SyntaxError: Unexpected token N. I guess this is because one of the properties looks like this:
{ ..., "SomeIntProp" : NumberLong(70) }
JavaScript parser simply doesn't understand Bson data type: NumberLong.
How should I convert BsonDocument to JSON so that the output would omit NumberLong?
There is no easy way to solve this, I worked out a solution by writing my own parsing function which understands the MongoDB BSON types and does the conversion. The native JSON.parse only understands the types used by the JavaScript. Here is my version:
https://gist.github.com/Hrish2006/8270187
You probably will not need the html snippets in the code.

Categories