Are JSON and Node.js Querystring the same? - json

On node.js, are JSON methods (parse, stringify) the same as Query Sting methods (parse, stringify) ?
Thank you.

Let's try:
var qs = require('querystring');
var obj = { 'foo' : '1 + 2' };
console.log(qs.stringify(obj));
// result: foo=1%20%2B%202
console.log(JSON.stringify(obj));
// result: {"foo":"1 + 2"}
So, no, they aren't :-)

Talking names. The query string methods return strings suitable for use in a URL query string. I. e., they are percent-escaped. That's not at all related to JSON.

Related

Cypress: assertion error on json field comparison

i am trying to do assertion on a json. basically i have to compare two json:
cy.get('h4#idParameters').each(($e, index, $list) => {
const text = $e.text()
expect(text).to.eq(parameters)
})
but I get the following error:
in the assertion if I use "contain" instead of "eq" the result doesn't change
There exist a space after ":" char in the first parameter. These strings are not equal.
If you want to compare this as a string, ensure it does not have extra spaces, points, or is in a different order.
But the better approach is to compare as JSON. One interesting approach should be using the deep-equal-in-any-order plugin. This plugin compares objects independent of it order. But first ensure to transform JSON strings to objects.
in the end I solved it like this. Thanks for the advice #Erme.
cy.get('h4#idParameters').each(($e, index, $list) => {
const text = $e.text()
var p1 = JSON.stringify(text)
var p2 = JSON.stringify(parameters)
p1=p1.replace(/\s/g, '');
p2=p2.replace(/\s/g, '');
p2 = p2.substr(1,p2.length)
expect(p1).to.contain(p2)
})

Parsing string data response

I am stuck in parsing a data response receiving from some third party vendor.
response is something like:-
data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');
I have tried several ways of parsing/stringify but it does not provide me a JSON response. I tried weird combinations of Querystring functions as well but that did not help.
I am badly stuck in this.
I will post a workaround it might not be efficient but will give you the result.
var data = "data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');";
var temp = data.substring(8,);
temp = temp.replace("(","{");
temp = temp.replace(")","}");
temp = temp.replace(/=/g,":");
temp = temp.replace(";","");
temp = eval('(' + temp + ')');
var Result = JSON.stringify(temp)
Result : {"responseCode":"A01","responseMessage":"Approved","accountNumber":"qwerty"}
You can use regex to convert it to a valid JSON structure.
let data = `data: ()(responseCode='A01', responseMessage='Approved', accountNumber='qwerty');`;
let modified = data
.replace(/\s/g,'')
.replace("data:()(",'{\'')
.replace(");",'}')
.replace(/=/g,"':")
.replace(/,/g,",'")
.replace(/'/g,'"')
let json = JSON.parse(modified);
console.log(json)

Can I submit a JSON to an Oracle Insert like I do with MySQL using Node?

I have the following code that I used for inserting into MySQL (MariaDB)....
import mysql from "mysql";
const INSERT_QUERY = "INSERT INTO CALL_DATE SET ? ON DUPLICATE KEY UPDATE MADE_DATE = VALUES(MADE_DATE)";
insertCallDate(callId, server, date){
const callDate = {
...
};
return connection.query(
INSERT_QUERY,
callDate
);
}
When I move to oracleDB I would like to do something like that again but the closest I can find is something like...
const INSERT_QUERY = "INSERT INTO CALL_DATE SET (ID, ...) values (:1, ...)";
Is there something similar to MySQL so I can pass a prestructured JSON object to Oracle? Specifically using the Node JS oracledb library?
There's a short section on JSON in the node-oracledb documentation. To quote an example:
const data = { "userId": 1, "userName": "Chris", "location": "Australia" };
const s = JSON.stringify(data); // change JavaScript value to a JSON string
const result = await connection.execute(
`INSERT INTO j_purchaseorder (po_document) VALUES (:bv)`,
[s] // bind the JSON string
);
There are also two runnable examples: selectjson.js and selectjsonblob.js.
Most of the JSON technology in Oracle is not specific to node-oracledb, so the Oracle manual Database JSON Developer’s Guide is a good resource.
You may be interested in SODA, which is also documented for node-oracledb and has an example, soda1.js. It lets you store 'documents' in the DB. These documents can be anything, but by default JSON documents are used.

How to make a query in MongoDB using a JSON?

is there anyway to make a query in MongoDB using a JSON and returning a object if one field of the json matches with some in the database?
for example, I have the this object called keysArray
{ house: 'true', garden: 'false' }
and I would like to make a query in Mongo passing this object as a query field and return if some object in my database matches with at least one of those fields :
keysArray.forEach(function(key){
collection.find({keysArray}, function(err, propertyMatch){
console.log(propertyMatch)
})
})
I got no objects back, even if I have one object in my database that matches these fields.
Thanks in advance
...and I would like to make a query in Mongo passing this object as a
query field and return if some object in my database matches with at
least one of those fields.
It sounds like OR logic - if I understood it well.
On this specific case it's not possible to pass in JSON-like object to query as it would be a implicit AND logic condition.
So you should build first a OR expression and use it in collection.find(), something like this:
var myjson = {'status': 32, 'profile': {$exists: false}};
function build_logic_or(json) {
var orExpr = [];
for (var field in json) {
var expr = {};
expr[field] = json[field];
orExpr.push(expr);
}
return {'$or': orExpr};
}
It would build an expression like this:
{"$or":[{"status":32},{"profile":{"$exists":false}}]}
So:
db.collection.find(build_logic_or(myjson))

how to delete nested json element by variable

how to delete a particular json element by variable:
i.e. I want to delete obj.a.b, but it is passed by a variable.
Is there a simple way to implement this?
var t = 'obj.a.b';
var obj = {a: {b: 'b', b2: 'b2'}};
delete t; // not work here
console.log(JSON.stringify(obj));
If you trust the value of t, you can use the eval(...) function to execute dynamic code like this:
var t = 'obj.a.b';
var obj = {a: {b: 'b', b2: 'b2'}};
eval("delete " + t + ";");
console.log(JSON.stringify(obj));
Note that if you cannot trust the value of t (e.g. it's a user-supplied value), an attacker can inject code by supplying a malicious value for t. You have to use eval(...) carefully as it can easily lead to such code-injection attack. This answer has good discussion about how and when to use eval.