If I have a number of responses:
const exampleResponses = [ "name1", "name2", "name3"];
But let's say it's thousands of responses, not just three. Is there a way to pull in the responses from another file? As it stands, with thousands of responses it just clogs up my coding file.
There are many ways you can go about this. One way would be to have a separate file with one array containing all the responses, then export that variable and require it in your main file
Responses.js
const responses = ['r1', 'r2', 'r3']
// And so on...
module.exports = {
responses
}
Main File
const { responses } = require('filePathToResponsesJS')
A way to do this is to make a JSON file and call from it with JavaScript.
const { exampleResponses } = require('./example.json')
{
"exampleResponses": [
"name1",
"name2",
"name3"
]
}
You can import the FileSystem module and do something like this:
responses= JSON.parse( fs.readFileSync( 'data/responses.json', function( err, data ) { ... }
Similarly, you can write to said file to keep things neat and tidy.
Related
I have this index.js and it's logging the whole .json file. I want to log the age (21). How do I do that?
const fs = require('fs');
async function doSomething() {
const data = fs.readFileSync("./apple.json")
const data2 = await JSON.parse(data)
console.log(JSON.stringify(data2, null, 2))
}
doSomething()
and a side question:
Is there a way to avoid using fs to read files?
/*
apple.json
{
"memberList":[
{
"age":"21",
"name":"Jom"
}
]
}
*/
/*
Output:
{
"memberList": [
{
"age": "21",
"name": "Jom"
}
]
}
*/
Your first question is quite obvious and this answer will not address it. Regarding your second question, yes. Using commonjs you just have to require the file. Like this:
const data = require('./apple.json');
If you are using ES6 modules, then you have to addd a assert statement. Like this:
import data from './apple.json' assert {type: 'json'};
Did you try to access the members of memberList?
console.log(data2.memberList[0].age);
I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.
main.js
import myDictionary from "myDictionary.js"
const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)
myDictionary.js
const myDictionary = {
key: variables.item
}
so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.
as always any help is greatly appreciated
You should modify the dictionary so that it keeps actual callback functions instead. Only then it will be able to accept arguments.
const myDictionary = {
key: (variables) => variables.item
}
const variables = {
item: "Hello"
}
const key = "key";
const data = myDictionary[key](variables)
console.log(data)
What you are trying to do is not possible. The myDictionary.js file has no idea whats inside you main file. The only thing you could do would be:
myDictionary.js
const myDictionary = {
key: "item"
}
main.js
import myDictionary from "myDictionary.js";
const variables = {
item: "Hello"
};
const data = variables[myDictionary["key"]];
console.log(data);
Also, even though JavaScript does not enforce semi-colons, they will save you a lot of headaches of some stupid rule that breaks the automatic inserter.
I must apologise as when I asked the question I wasn't fully clear on what I needed but after some experimentation and looking at my edge cases and after looking at Krzysztof's answer I had a thought and came up with something similar to this -
const dict = {
key: (eventData) => {
return [
{
module: 'company',
entity: 'placement',
variables: {
placement_id: {
value: eventData.id,
},
},
},
{
module: 'company',
entity: 'placement',
variables: {
client_id: {
value: eventData.client.id,
},
},
},
];
},
}
Then I'm getting the data like this -
const data = dict?.[key](eventData)
console.log(data)
I can then navigate or manipulate the data however I need.
thank you everyone who spent time to help me
Basically, this shouldn´t be a very difficult question, but I´ve tried for like 2 or 3 hours and couldnt reach my goal, especially for such an "easy" question. Im using Node.js and my goal is, to load data from a Json file into a variable, add some new data to this and store my data into the same json file again.
Herefor, my json file looks like this:
[
{
"name": "Max",
"date": "1.1.2020"
}, {
"name": "Henry",
"date": "2.2.2020"
}
]
Here´s my code:
const fs = require('fs');
const filename = './jsonFile.json';
const data = loadJSON();
// console.log(data) keeps saying undefined (whithout using .toString in loadJSON)
function loadJSON() {
JSON.parse(fs.readFileSync(filename).toString); // toString doesnt work
}
function saveJSON(data) {
fs.writeFileSync(filename, JSON.stringify(data));
}
function adduser(username) {
var today = "3.3.2020"; // doesnt matter
let obj = {
name: username,
date: today
}
vipJson.push(obj);
saveVIP(vipJson);
}
It doesnt seem to be working. Could anyone help me, to fix my problem, so I can work with .json files ? Thanks a lot!
You need to specify the BufferEncoding options to read the file, something like this.
const fs = require("fs")
const data = fs.readFileSync("./myfile.json", { encoding: "utf8", flag: "r" })
If you are sure about json files, you can read data from file using require.
const fs = require('fs');
const filename = './jsonFile.json';
const data = loadJSON();
function loadJSON() {
return require(filename)
}
function saveJSON(data) {
fs.writeFileSync(filename, JSON.stringify(data));
}
function adduser(username) {
var today = "3.3.2020"; // doesnt matter
let obj = {
name: username,
date: today
}
data.push(obj);
saveJSON(data);
}
Try above code snippet.
I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.
(Example of my test file, being the columns A and B respectively):
Johny Wilson | jonhny#email.com
Andrew Jehnsen | andrew#example.com
Billy Soon | billy#mail.com
In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:
var xlsx = require('node-xlsx');
router.post('/enviar', upload.single("lista"),(req, res, next) =>{
//dir is the path of the xlsx file
const workSheetsFromFile = xlsx.parse(dir);
res.send(workSheetsFromFile);
});
returns an object that looks like this:
[
{
"name": "Hoja1",
"data": [
[
"Johny Wilson",
"jonhny#email.com"
],
[
"Andrew Jehnsen",
"andrew#example.com"
],
[
"Billy Soon",
"billy#mail.com"
]
]
}
]
As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.
I've already tried to loop on the data array with:
workSheetsFromFile.data.forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile[data].forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile['data'].forEach((element) =>{
console.log(element);
});
but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(
For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.
What you have here seems to be an array of objects, not an object itself!
try
workSheetsFromFile[0].data.forEach((element) => {
console.log(element);
});
If you have more elements, consider first looping the array and then extracting data
const structuredData = workSheetsFromFile[0].data.map(res => {
return res
});
workSheetsFromFile.forEach(sheet => {
//access data
console.log(sheet.data)
//or
sheet.data.forEach(data => {
//access each data
console.log(data)
})
})
I have been playing around with a module from NPM called JSON-Query, I originally able to make the module function with JSON embedded in my js.
I have spent about two days attempting to make it query JSON that is external and in a JSON file.
The original code that was functioning looked something like this.
var jsonQuery = require('json-query')
var data = {
people: [
{name: 'Matt', country: 'NZ'},
{name: 'Pete', country: 'AU'},
{name: 'Mikey', country: 'NZ'}
]
}
jsonQuery('people[country=NZ].name', {
data: data
}) //=> {value: 'Matt', parents: [...], key: 0} ... etc
I was able to query the internal JSON to find the key I was looking for.
I realized I need the ability to update the JSON while the code is live, so I moved the JSON to its own file.
Currently my main JS file looks like this.
var jsonQuery = require('json-query');
var fs = require('fs');
function querydb(netdomain){
fs.readFile('./querykeys.json', 'utf8', function (err, data) {
if (err){console.log('error');}
var obj = JSON.parse(data);
console.log(jsonQuery('servers[netshare=Dacie2015].netdomain', {
obj: obj
}));
});
}
querydb();
My JSON file that contains the json looks like this.
{
"servers": [
{"netdomain": "google.com", "netshare": "password", "authip":"216.58.203.46"},
{"netdomain": "localhost", "netshare": "localghost", "authip":"127.0.0.1"},
{"netdomain": "facebook.com", "netshare": "timeline", "authip":"31.13.69.228"}
]
}
The issue I have ran into, I am unable to query the JSON anymore, when the function QueryDB() is ran, no matter what is in the place to query the JSON, i get no response locating my key.
Currently the response I get from the server when i try to query the JSON file is
{ value: null,
key: 'netdomain',
references: [],
parents: [ { key: 'servers', value: null }, { key: null, value: null } ] }
To be abundantly clear, i believe my issue is the way i call my object into play, i have played with the structure of the JSON-Query and have been unable to accomplish being able to isolate a key.
Any help on this would be amazing, the module that i am working with can be found on npm at [NPM]https://www.npmjs.com/package/json-query
Thank you
I think this is just a typo. Shouldn't this:
obj: obj
be this?
data: obj