Recognizing Date values in CSVtoJSON - node - node.js

I'm trying to convert CSVs to JSONs in Node, and am running into a problem dynamically parsing date values (in addition to the built-in checkType: true for numbers and boolean values).
Using CSVtoJSON (csvtojson), I'm able to write an explicit declaration in the colParser parameter,
const jsonArray=await csv({checkType: true, colParser:{
'Measurement Timestamp':(item => {return new Date(item);})
}
}).fromFile(csvFilePath);
and this works well, but I want to be able to recognize the content on its own without me needing to explicitly write the header name.
I'm even happy to use a filter like let isTimeDate = (data) => /time|date/i.test(data) to run on the header names prior to the parsing, but I'm running into a wall trying to have the colParser cycle through that list.
I also don't want to have to run a isDate function on every single element, because that's just wasteful.

Related

Unexpected error: Operation is not valid due to the current state of the object

I am getting the above error when I am trying to run this function on a text column in power query[Excel].
The column contains different names and this function checks if the entry has either of "AbbVie", "Roche" or "Pfizer" in it. It returns the names from the list that is present in the entry.
(txt as text) =>
[
create_val = (val as text,check as text, output as text) =>
let
output = if Text.Contains(val,check)
then Text.Combine({output, check},",")
else output
in
output,
final_value = List.Accumulate({"AbbVie","Roche","Pfizer"},"",(state,current) => create_val(txt,current,state))
][final_value]
I struggled with this one too so I though I'd share how I solved it.
I was using a custom function recursively, as a means to implement looping. It turns out I was modifying variables from the function definition, i.e. variables that the function had been called with. By declaring local variables, the function worked as expected.

NodeJS why is object[0] returning '{' instead of the first property from this json object?

So I have to go through a bunch of code to get some data from an iframe. the iframe has a lot of data but in there is an object called '_name'. the first key of name is 'extension_id' and its value is a big long string. the json object is enclosed in apostrophes. I have tried removing the apostrophes but still instead of 'extension_id_output' I get a single curly bracket. the json object looks something like this
Frame {
...
...
_name: '{"extension_id":"a big huge string that I need"} "a bunch of other stuff":"this is a valid json object as confirmed by jsonlint", "globalOptions":{"crev":"1.2.50"}}}'
}
it's a whole big ugly paragraph but I really just need the extension_id. so this is the code I'm currently using after attempt 100 or whatever.
var frames = await page.frames();
// I'm using puppeteer for this part but I don't think that's relevant overall.
var thing = frames[1]._name;
console.log(frames[1])
// console.log(thing)
thing.replace(/'/g, '"')
// this is to remove the apostrophes from the outside of the object. I thought that would change things before. it does not. still outputs a single {
JSON.parse(thing)
console.log(thing[0])
instead of getting a big huge string that I need or whatever is written in extension_id. I get a {. that's it. I think that is because the whole object starts with a curly bracket. this is confirmed to me because console.log(thing[2]) prints e. so what's going on? jsonlint says this is a valid json object but maybe it's just a big string and I should be doing some kind of split to grab whaat's between the first : and the first ,. I'm really not sure.
For two reasons:
object[0] doesn't return the value an object's "first property", it returns the value of the property with the name "0", if any (there probably isn't in your object); and
Because it's JSON, and when you're dealing with JSON in JavaScript code, you are by definition dealing with a string. (More here.) If you want to deal with the object that the JSON describes, parse it.
Here's an example of parsing it and getting the value of the extension_id property from it:
const parsed = JSON.parse(frames[1]._name);
console.log(parsed.extension_id); // The ID

How to convert date to hours from now using moment js

I have the following data 2020-07-06T02:46:57.883+00:00. How do I convert it using moment js to 5 hours ago. for example. I used the following code but it doesnot work.
moment('2020-07-06T02:46:57.883+00:00.', "YYYYMMDD").fromNow();
but it is not working correctly
It seems like you are trying to achieve two outcomes through single command.
Ideally, if you want to first format the date and then use the fromNow() method, I would suggest the following way:
const date = moment('2020-07-06T02:46:57.883+00:00');
const formatedDate = date.format('YYYYMMDD');
const time = date.fromNow();
OR You can chain these operations
const time = moment('2020-07-06T02:46:57.883+00:00').fromNow();
Note: format() method returns a string, fromNow() cannot be chained to format method's response.

How do I concatenate a string in handlebars view

I wrote a helper function to help me format URL, which is the combination of some object attributes. How do I concatenate this attribute in handlebars view?
Helper function
const url = (link)=>{
return process.env.URL+'/'+link.replace(/ /gi,'-').toLowerCase();
};
My view
{{this.name}}
What you can do to accomplish this is to create a helper to concatenate your strings and pass the concatenated string to the url helper.
In JavaScript, every non-arrow function has a local variable named arguments assigned an object, in this object you'll find (you guessed it) the arguments passed to the function when it was invoked.
Using this arguments object we can create a helper for Handlebars.js that lets us concatenate as many strings as we want.
Because (as described by the documentation) the arguments object is an array-like object, we have to create an actual array from it that we can use to concatenate everything together using Array.join to make it as simple as possible.
Handlebars.registerHelper('concat', function() {
return [...arguments].join('');
});
But why would it be that simple, right?
What I discovered when I was trying out this solution is that the last element in the arguments object is an object with some information about the helper that was used, like the name.
To make this work with that little bit of information in mind we have to slice the array so that the last element gets removed and then concatenate it.
Handlebars.registerHelper('concat', function() {
arguments = [...arguments].slice(0, -1);
return arguments.join('');
});
We now have a helper that we can use to concatenate whatever we want, the only thing left to do is pass it to the other helper, the url helper in this case.
{{url (concat 'samples/' this.name '/' this.class '/' this.id)}}
^ I found a comment on an GitHub issue regarding chaining helpers and that Handlebars.js apparently has native support for this.
I hope this helped and that I didn't spoon-feed to much without explaining it properly.

Get real bool value from YamlStream

I use YamlDotnet to parse a yaml stream to a dictionary of string object via the YamlStream.
The YamlMappingType, YamlSequenceNode and YamlScalarNode are used in order to convert the value to a dictionary, a list or a string.
But I need to get a real boolean value instead of the string equivalent, and for that I use
bool.TryParse(value.ToString(), out valueBool)
value veing a YamlNode.
Is there a better way to do that?
Perhaps another child type of YamlNode?
EDIT:
I don't know the content of the YAML file, I just want to get a dictionary with his values.
Instead of doing the parsing manually, you should use the Deserializer class, which will convert a YAML document into an object graph.
var deserializer = new Deserializer();
var parsed = deserializer.Deserialize<...>(input);
You can see a working example here

Resources