How to check if JSON includes something NODEJS - node.js

I want to check if my JSON includes "hello". All of the JSON.
Normally if it was a string I'd do this:
var string = "hello there this is a test"
if(string.includes("hello")) return console.log("Hello found")
is there a JSON version for that?

You can convert the JSON into javascript object using JSON.parse() and then search on it.
For example:
let jsonOb = {"msg": "hello there this is a test"}
let ob = JSON.parse(jsonOb)
let string = ob.msg
if(string.includes("hello")) return console.log("Hello found")
Hope it solves your problem.

Related

How to properly read and parse data from Firebase in Nim?

I have a database in Firebase which currently I can access through CURL like this
curl "https://mydb.firebaseio.com/my_data.json?auth=XKJYED78634jsvdffwu7riugwer"
I want to make a Nim script to actively listen to this data for any changes and then generate web pages accordingly, what would be the best way to do that ? I am not able to find any library for Firebase support in Nim.
Thanks #jason, based on your response, this is what I did:
import std/[httpclient, json]
const url = "https://mydb.firebaseio.com/my_data.json?auth=XKJYED78634jsvdffwu7riugwer"
var client = newHttpClient()
let parsedJsonObj = parseJson(client.getContent(url))
client.close()
echo parsedJsonObj
Then I compiled this with -d:ssl flag and this is successfully reading the JSON data and dumping it to stdout. Another problem I am facing is that this JSON data is unstructured, is there any way to iterate through all records without knowing the key names ?
I'm no expert in webdev, but given that's a link that returns a json formatted file you can do something like the following:
import std/[httpclient, htmlgen, asyncdispatch, json]
const url = "https://mydb.firebaseio.com/my_data.json?auth=XKJYED78634jsvdffwu7riugwer" # do this safer using dotenvs or similar
proc buildSite(): Future[string] {.async.} =
let
myHttpClient = newAsyncHttpClient()
data = parseJson(await(myHttpClient.getContent(url)))
# Do stuff with `data, we'll just make a header for an example
result = h1("Hellow World")
myHttpClient.close()
proc main() {.async.} =
var isWatchingSite = true
while isWatchingSite:
try:
let site = await buildSite()
except HttpRequestError as err:
echo err.msg
await sleepAsync(10000)
waitFor main()

Node js equivalent to Python utf8, Sha1, base64

I have this piece of code in python3
payload = 'my URI'
payload_utf8 = payload.encode("utf-8")
print(payload_utf8)
payload_sha1 = hashlib.sha1(payload_utf8).digest()
print(payload_sha1)
payload_base64 = base64.b64encode(payload_sha1)
print(payload_base64)
I want the same result but in node.js. I have tried this
const payload = "my URI";
console.log(payload);
const payload_UTF8 = utf8.encode(payload);
console.log(payload_UTF8);
const payload_Sha = crypto.createHash('sha1').update(payload_UTF8).digest()
console.log(payload_Sha);
const payload_Base64 = Buffer.from(payload_Sha).toString('base64');
But the results isn't the same.
The results are the same, the only difference is that in the python example you're returning a byte array and in the Js example, you're returning a string. If you want to get the exact same result in string format you can use print(payload_base64.decode("utf-8")).

JSON.parse is not a function in node js

I'm new in node js and I'm trying to parse a JSON. This is what I've done so far:
const JSON = require("nodemon/lib/utils");
...
someFunction() {
let sens = [];
// sensor is the result of fs.readFileSync call and file is a json array
sens = JSON.parse(sensors);
It throws me:
JSON.parse is not a function.
How can I solve it?
Just comment out the very first line. JSON is built in already.
//const JSON = require("nodemon/lib/utils");
JSON is kind of a global object. It doesn't need to be required. So, just remove the line where JSON is required and it'll work fine.

Require() from string into object

Assuming I have the content of a js file in a string. Furthermore, assume it has an exports['default'] = function() {...} and/or other exported properties or functions. Is there any way to "require" it (compile it) from that string into an object, such that I can use it? (Also, I don't want to cache it like require() does.)
Here's a very simple example using vm.runInThisContext():
const vm = require('vm');
let code = `
exports['default'] = function() {
console.log('hello world');
}
`
global.exports = {}; // this is what `exports` in the code will refer to
vm.runInThisContext(code);
global.exports.default(); // "hello world"
Or, if you don't want to use globals, you can achieve something similar using eval:
let sandbox = {};
let wrappedCode = `void function(exports) { ${ code } }(sandbox)`;
eval(wrappedCode);
sandbox.default(); // "hello world"
Both methods assume that the code you're feeding to it is "safe", because they will both allow running arbitrary code.

Invalid character entity parsing xml

I am trying to parse a string of xml and I getting an error
[Error: Invalid character entity
Line: 0
Column: 837
Char: ]
Does xml not like brackets? Do I need to replace all the brackets with something like \\]. Thanks
Ok, the invalid character was the dash and an &. I fixed it by doing the following:
xml = data.testSteps.replace(/[\n\r]/g, '\\n')
.replace(/&/g,"&")
.replace(/-/g,"-");
Thanks
Using a node domparser will get around having to do a string replace on every character that is not easily parsed as a string. This is especially useful if you have a large amount of XML to parse that may have different characters.
I would recommend xmldom as I have used it successfully with xml2js
The combined usage looks like the following:
var parseString = require('xml2js').parseString;
var DOMParser = require('xmldom').DOMParser;
var xmlString = "<test>some stuff </test>";
var xmlStringSerialized = new DOMParser().parseFromString(xmlString, "text/xml");
parseString(xmlStringSerialized, function (err, result) {
if (err) {
//did not work
} else {
//worked! use JSON.stringify()
var allDone = JSON.stringify(result);
}
});

Resources