CSV:
TableName, RowCount, TableStatus
table1, 10, Y
table2, 21, N
table3, 23, Y
table4, 24, N
table5, 25, Y
Need to convert CSV to JSON in this format:
{
"table1": {
"row_count": "10"
}
},
{
"table3": {
"row_count": "23"
}
},
{
"table5": {
"row_count": "25"
}
}
const csvFilePath='sample.csv'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
})
I am using Node csvtojson NPM
I am able to convert to JSON, but I need the json in the above format out of the box. Is it possible?
And also If "TableStatus" value is "N", it should not add that row in JSON.
Note: I am able to convert to desirable JSON format by iterating the JSON object, but is there any way to convert using this NPM.
Thanks.
Related
I think I'm going crazy... I'm just trying to do some basic API learning for NodeJS and I've got this, which works fine and prints "United States Dollar" to console...
app.get("/", function(req, res){
const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const priceData = JSON.parse(data);
console.log(priceData.bpi.USD.description);
})
})
but when I'm trying to access it by using the array position of USD (which is [0])like this...
app.get("/", function(req, res){
const url = "https://api.coindesk.com/v1/bpi/currentprice.json"
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
const priceData = JSON.parse(data);
console.log(priceData.bpi[0].description);
})
})
I get a crash of ...
TypeError: Cannot read property 'description' of undefined
The JSON is
{
"time": {
"updated": "Oct 21, 2021 16:10:00 UTC",
"updatedISO": "2021-10-21T16:10:00+00:00",
"updateduk": "Oct 21, 2021 at 17:10 BST"
},
"disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"chartName": "Bitcoin",
"bpi": {
"USD": {
"code": "USD",
"symbol": "$",
"rate": "63,222.0050",
"description": "United States Dollar",
"rate_float": 63222.005
},
"GBP": {
"code": "GBP",
"symbol": "£",
"rate": "45,779.4964",
"description": "British Pound Sterling",
"rate_float": 45779.4964
},
"EUR": {
"code": "EUR",
"symbol": "€",
"rate": "54,306.7540",
"description": "Euro",
"rate_float": 54306.754
}
}
}
The USD object is position[0] of the bpi array (right?) so why can't I just tap into it like above? This example seems pretty similar to mine so can't see where I'm going wrong?
The problem is the content of priceData.bpi is not an array [], it's an object {}, so you can't access USD by position, the only way to access it is priceData.bpi.USD.
More about JS arrays, objects.
However, if you really need to access it by position, you can convert the contents of priceData.bpi into an array using the Object.entries() method.
Example
let priceData = {"time":{"updated":"Oct 21, 2021 16:39:00 UTC","updatedISO":"2021-10-21T16:39:00+00:00","updateduk":"Oct 21, 2021 at 17:39 BST"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","chartName":"Bitcoin","bpi":{"USD":{"code":"USD","symbol":"$","rate":"63,340.4233","description":"United States Dollar","rate_float":63340.4233},"GBP":{"code":"GBP","symbol":"£","rate":"45,865.2439","description":"British Pound Sterling","rate_float":45865.2439},"EUR":{"code":"EUR","symbol":"€","rate":"54,408.4735","description":"Euro","rate_float":54408.4735}}}
let bpiArr = Object.entries(priceData.bpi)
console.log(bpiArr[0][1].description)
Note: the first [0] element of bpiArr[0] contains the string "USD" and the second [1] contains an object which got the description key and its value.
More information
bpi is not an Array but an object. If it uses curly brackets it is an object. If using square brackets it is an array. To access the USD property of bpi object you use dot notation (like you have done: bpi.USD) or you use bpi["USD"]
Based on your JSON bpi is an object but you are accessing it via array index which is wrong. If you want the value of USD, the way you were accessing in the first snippet is correct. However, if you want to use it as an array, you can do like below:
const {bpi= {}} = json;
const bpiArr = Object.entries(bpi);
// to access all the values
for (const [key,val] of bpiArr) {
console.log(key,val.description)
}
I want to parse this JSON data to a file like this :
JSON
{
"nodes": [
{"id": 1, "name" : "a", "radius" :0.5, "angle" : 2.64159265359},
{"id": 2, "name" : "b", "radius" : 0.6, "angle" : 3.64159265359}
],
"links": [
{"source": "a", "target": "b", "delay": "10ms"}
]
}
File :
[nodes]
a: _ radius=0.5 angle=2.64159265359
b: _ radius=0.6 angle=3.64159265359
[links]
a:b delay=10ms
So far my code is just reading the JSON file
const fs = require('fs');
data = JSON.parse(fs.readFileSync("topo.json","utf-8"));
for (node in data)
{
for (link in data[node])
{
console.log(data[node][link]);
}
}
How can I get those values saved and create a new file having those values in them ?
You did not specify what file type you want to use, so I went with a simple .txt file.
The only small Issue with the code posted, is that these are arrays, so you have to loop a bit differently over them. Apart from that simply write the data into placeholders in your format string and append it to a global object that will be written to the file. Then you should be good to like that:
const fs = require('fs');
const data = JSON.parse(fs.readFileSync('topo.json','utf-8'));
let textFileContent = '';
textFileContent += '[nodes]\n';
data.nodes.forEach(node => {
textFileContent += `${node.name}: _ radius=${node.radius} angle=${node.angle}\n`;
});
textFileContent += '[links]\n';
data.links.forEach(link => {
textFileContent += `${link.source}:${link.target} delay=${link.delay}\n`;
});
fs.writeFile('parsed.txt', textFileContent, function(err) {
if(err) {
return console.log(err);
}
});
Note that this could probably be done more elegant and it won`t scale very well, if your JSON is more complex, than whats shown in the sample...
excuse me, I am a beginner at nodejs express, I want to ask how do I change the data in the response json from
the date format 2017-12-14T05: 23: 01.000Z
to the date format dd / mm / yyyy
and that I mean when it is issued as a response json key with the name "TANGGAL_PEMBAYARAN" changes to dd / mm / yyyy?
this is my json response
{
"result": {
"STATUS": "Y",
"TANGGAL_PEMBAYARAN": "2017-12-14T05:23:01.000Z",
"NTPD": "1110374001101224",
"JENIS_BAYAR": "T"
}
thank you very much
We can use toLocaleDateString to format as dd/mm/yyyy, for example a en-GB locale will do this.
We can also specify a timeZone (in this example I'm using UTC)
You could also use Moment.js or Luxon to do this conversion.
let response = {
"result": {
"STATUS": "Y",
"TANGGAL_PEMBAYARAN": "2017-12-14T05:23:01.000Z",
"NTPD": "1110374001101224",
"JENIS_BAYAR": "T"
}
};
function isoDateToLocaleDateString(isoDate, locale, timeZone) {
return new Date(isoDate).toLocaleDateString(locale, { timeZone } );
}
// Convert date format
response.result.TANGGAL_PEMBAYARAN = isoDateToLocaleDateString(response.result.TANGGAL_PEMBAYARAN, "en-GB", "UTC")
console.log("Response date:", response.result.TANGGAL_PEMBAYARAN);
You can use momentjs (https://momentjs.com/)
const moment = require('moment');
let response = {
"result": {
"STATUS": "Y",
"TANGGAL_PEMBAYARAN": "2017-12-14T05:23:01.000Z",
"NTPD": "1110374001101224",
"JENIS_BAYAR": "T"
}
response.result.TANGGAL_PEMBAYARAN = moment(response.result.TANGGAL_PEMBAYARAN).format('DD/MM/YYYY')
I'm trying to get records with a date between two dates (provided by URL). A am using Lodash and Moment. I tried it in the following way but the result is empty. Does somebody have any idea? Thank you.
app.get('/paymentListByDate/:from/:to/', (req, res) => {
let response = getDataPayment();
let from_url = req.params.from;
let to_url = req.params.to;
let dateFormat = "DD-MM-YYYY";
let filtered = _.filter(response, { 'dueDate': moment().isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat))});
sendDelayedResponse(res, filtered, 1);
});
sendDelayedResponse() method should be fine. Parameters as well. JSON object is the following:
{
"value": {"amount": 1000, "currency": "CZK"},
"partyAccount": {"prefix": "035", "accountNumber": "123456789", "bankCode" :"2010"},
"dueDate": "15.01.2020",
"recurringPayment": {"firstPayment": "First payment", "lastPayment": "Last payment", "interval": "WEEK"},
"payeeMessage": "Message2",
"payerMessage": "Message1",
"categoryId": 0,
"additionalInfo": {"constantSymbol": "123456789", "variableSymbol": "123456789", "specificSymbol": "123456789"},
"id": 1,
"accountId": 123456789,
"editableByUser": true,
"realizationStatus": "RTS_REALISED"
}
moment() returns current date time. You have to compare from_url with to_url (I don't know why you use _url instead of _date).
filter just working with a collection, I hope getDataPayment() returns a array in any cases.
Without lodash:
const filtered = response.filter((o) => {
return moment(o.dueDate, 'DD.MM.YYYY') // Convert to moment with exactly date format
.isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat));
});
with lodash:
const filtered = _.filter(response, (o) => {
return moment(o.dueDate, 'DD.MM.YYYY')
.isBetween(moment(from_url, dateFormat), moment(to_url, dateFormat));
});
i'm using node-cassandra-cql driver ( https://github.com/jorgebay/node-cassandra-cql ) to do sample select into a cassandra column family.
My cf has three column with that datatypes:
1 - value -> text
2 - date -> timestamp
3 - hits -> counter
Using nodeJS to fetch rows i do:
client.execute('SELECT date,value,hits FROM cf LIMIT 100', [],
function(err, result) {
if(err){
var error = {error:true,message:err};
res.send(error);
}
else{
var trends = {};
for(var i=0;i<result.rows.length;i++){
var row = result.rows[i];
console.log(row.date);
console.log(row.hits);
}
}
}
);
The console log gives me:
{
"low": 1342763392,
"high": 323,
"unsigned": false
}
{
"low": 1,
"high": 0,
"unsigned": false
}
What i need to do to get correct value?
Thanks!
Cassandra counter column value are a 64-bit signed integer (bigints), in the Node.js driver are represented as Google Closure's Long.
To get the string representation of the decimal value of the bigint, you can use #toString() method.
//"1", "2", ...
row.hits.toString();
Answer by jorgebg is also applicable when executing COUNT(*).
For example:
SELECT COUNT (*) FROM my_table;
In that case to extract the value I used:
result.rows[0].count.toString();
const str = result.first().count;
const count = JSON.parse(str);