Discord JS calling JSON - javascript

I'm currently working on a discord js bot which will fetch some information from a JSON file on a website. I have been able to get it to work with photos but I have no idea how to get the information I want from this JSON file. I'm sorry if this is really simple but I'm new to JS
The part I need from the JSON file is "name" and then I need it too print out all of the names that are in the file at the time.
This is currently a JSON file that I am testing with, it's a FiveM server player list.
http://145.239.206.148:30120/players.json
If you could please provide me with some information on how to get all of the player names that would be much appreciated.
This is the blank "Fivem" command file.
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
}
module.exports.help = {
name: "fivem"
}

You could parse the JSON file with JSON.parse() and traverse over each of the returned Object's array elements to access the name attributes and values. A JSON Parser would be helpful to visualize the indices of it's structure. Resources : JavaScript JSON Parsing

I used an api so I think you could do something like:
https.get('http://145.239.206.148:30120/players.json', response => {
response.setEncoding('utf8');
let body = '';
response.on('data', data => {
body += data;
});
response.on('end', () => {
body = JSON.parse(body);
console.log(body) // You obtain your json as an js object...
});
});
It worked for me so...
MrNossiom

Related

How to get update data from json file in discord.js

I have a help command and when I use this, According to the language entered in the data of the json file, the bot responds to that language, but when we change the language through the json file, it still responds with the previous language.
My json file:
{"serverid": "fa"} serverid for example 70436705474 :)
const lang = require('../data/lang.json')
module.exports = {
name: "help",
description: "For see help",
execute(client, message){
let server = message.guild.id // server id for example 70436705474
if (lang[server] == "fa"){
let embed1 = new Discord.MessageEmbed()
.setAuthor("سلام")
.setDescription(`چطور میتونم کمکتون کنم؟`)
message.channel.send(embed1)
} else if (lang[server] == "en") {
let embed2 = new Discord.MessageEmbed()
.setAuthor("Hi")
.setDescription(`How can I help you?`)
message.channel.send(embed2)
}
}
}
response is embed 1
when I edit json file to => {"serverid": "en"} again I get response embed1 but command not update
I need when I edit the language fa to en in json file I get "embed2"
Welcome to Stack Overflow!
Make sure your json file doesn't actually say "serverid", and contains the server's ID.
If it has the server ID, but you're changing the json file as the bot is running, you'll want to load the json file through the fs module, or delete the json file from require cache (delete require.cache[require.resolve('../data/lang.json')])
The issue is coming from the fact that the JSON file is being read from memory due to the way it's being imported, so changes to its physical copy won't affect the memory copy unless it's reloaded.

Parsing Json data from a file

I am building a Node JS application that reads file that contains array of Json objects, and displays it on a table. I need to parse the JSON data array.
sample json data:
[{"name":"Ken", "Age":"25"},{"name":"Pulsar", "Age":30}]
I have used the following to read from file and pass it into another json object:
const fileRead = fs.readFileSync("/Users/mken/Desktop/Node JS/DATA-TABLE/public/files/data.json", (err, data)=>{
console.log(JSON.parse(data))
return JSON.parse(data);
});
console.log(fileRead)
The expected output is array of JSON objects. However, when I console.log the fileRead, I do not get intended output:output
I further intend to iterate through the data read above and pass it to a JSON object:
const data = {headers:["Name", "Age"], rows: fileRead.foreach((row)=>{return row.name, row.age];})}
Please check and advise.
const fs = require('fs');
// Thanks to: https://nodejs.dev/learn/reading-files-with-nodejs
try {
const data = fs.readFileSync('test.txt', 'utf8');
console.log(data);
const json = JSON.parse(data);
console.log(json);
} catch (err) {
console.error(err);
}
the issue was with encoding. I passed utf-8 to filereadsync as second parameter, and it worked.
Thank you
If I do your task, I'll save data on a table, then I'll paste data to a json file and I'll read the file like your code.
I do that because I want to control the format of the JSON file. If you save a manual file in JSON, there are many ways you have problems with formatting JSON.
I hope my answer is helpful. Good luck!
 

How to read and write to local JSON files from React.js?

I have looked at multiple resources for this, however, none seem to be able to answer my question. I have a local JSON file in my React app called items.json. In that file, is a list of objects, which I want to be able to update. I have tried using fs however this apparently doesn't work in React, as I received this error:
Unhandled Rejection (TypeError): fs.readFileSync is not a function
What I am trying to do, is that when the code gets a new item, it looks through the JSON file to see if there is an existing object with a matching values in its name property. If there is, it increments that objects count property by 1, otherwise it creates a new object, and appends it to the list in the JSON file. This is the code that I have written to do that. The logic seems sound (although its not tested) but I can't figure out how to read/write the data.
let raw = fs.readFileSync("../database/items.json");
let itemList = JSON.parse(raw);
let found = false;
for (let item of itemList.averages) {
if (item.name === this.state.data.item_name) {
found = true;
item.count += 1;
}
}
if (!found) {
let newItem = {
name: this.state.data.item_name,
count: 1,
}
itemList.averages.push(newItem);
}
let newRaw = JSON.stringify(itemList);
fs.writeFileSync("../database/items.json", newRaw);
The JSON file:
{
"averages": [
{
"name": "Example",
"count": 1,
}
]
}
First of all, the browser itself doesn't have access to the filesystem, so you won't be able to achieve that using your react app. However, this can be achieved if you use Node.js(or any other FW) at the backend and create an API endpoint which can help you to write to the filesystem.
Secondly, if you wanted to only do things on the frontend side without creating an extra API just for saving the data in a JSON file which I think is not necessary in your case. You can use localstorage to save the data and ask the user to download a text file using this :
TextFile = () => {
const element = document.createElement("a");
const textFile = new Blob([[JSON.stringify('pass data from localStorage')], {type: 'text/plain'}); //pass data from localStorage API to blob
element.href = URL.createObjectURL(textFile);
element.download = "userFile.txt";
document.body.appendChild(element);
element.click();
}
Now, To use local storage API you can check here - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
reading and writing JSON file to local storage is quite simple with NodeJs, which means a tiny piece of backend API in express would help get this job done.
few piece of code that might help you. Assuming you JSON structure would be such as below;
{
"name":"arif",
"surname":"shariati"
}
Read JSON file;
// import * as fs from 'fs';
const fs = require('fs')
fs.readFile('./myFile.json', 'utf8', (err, jsonString) => {
if (err) {
return;
}
try {
const customer = JSON.parse(jsonString);
} catch(err) {
console.log('Error parsing JSON string:', err);
}
})
customer contains your JSON, and values can be accessed by customer.name;
Write to JSON File
Let's say you have an update on your JSON object such as below;
const updatedJSON = {
"name":"arif updated",
"surname":"shariati updated"
}
Now you can write to your file. If file does not exist, it will create one. If already exists, it will overwrite.
fs.writeFile('./myFile.json', JSON.stringify(updatedJSON), (err) => {
if (err) console.log('Error writing file:', err);
})
Importing and reading from json can be like:
import data from ‘./data/data.json’;
then use .map() to iterate data.
for writing locally you can use some libraries like https://www.npmjs.com/package/write-json-file

Turning JSON.parse() return type to an array of object

I have defined a file called note-data.json which contains json data. In the following code a variable of type of array called notes is declared. What I want to achieve is that the program read the json file save it in the noteString variable and then make a array of object with JSON.parse() from noteString and put it into notes array. So I can add new objects to the json file. But when the programme gets to the line note.push() it complains since, I think, the type of notes has turned to a string and push is not define for string. How can I get around this issue?
Please ignore the fact that if the json file is not provided the the program crashes.
My code:
const addNote = (title, body) => {
let notes= [];
const note = {
title,
body
};
const notesString = fs.readFileSync('node-data.json', 'utf8');
notes = JSON.parse(notesString);
notes.push(note);
fs.writeFileSync('node-data.json', JSON.stringify(note));
}
File note-data.json:
{"title":"Greeting","body":"Hello"}
I think you are fumbling with your variables here. From what I understood - you want to read JSON from a file and append that JSON to an array, right? Following code will help you do just that
const addNote = (title, body) => {
let notes= []; //Declare an array
const note = JSON.parse(fs.readFileSync('node-data.json', 'utf8')); //read and parse file contents
notes.push(note); //Append new JSON to your array
//This line below appears to have no purpose ??
fs.writeFileSync('node-data.json', JSON.stringify(note));
}

Node.js- Make JSON Array object in the server side available to HTML page for D3 charts

I'm very new to Node.js. My goal is to develop d3 charts in HTML handling Data objects(Json Array) that have 100K plus rows using a CSV spreadsheet. I want to load the CSV file and convert it to JSON Array object in the server side so this will not crash IE11 when loading the CSV file in the front end. The CSV is a big file. When I create a node js file that creates a server and load/convert the CSV into JSON Array using require('csvtojson') module, I want to send the JSON Array object to my html so i can grab that object and plug into D3 charts. I'm trying to avoid having the "Not enough storage..." jquery error when using ajax. Is this possible? I'm trying really hard to find an example but no luck. Only sites i found is how to display the json as a string into the html page. Is there a way to grab the JSON Array object in the HTML page? This is the code i use to create a server and to make all my html pages display on the browser.
Updated: I added the csv() and it converts the data into jsonObject. So far its just getting the one json object which this is not the case. I just want to push the 'jsonData' object so i can grab that in the HTML page and plug it to d3. Is this possible? Please, need help. I cant use d3.csv() in html because the file is too large and the IE11 browser will crash. Thats why I do this in the server.
csv().fromFile(csvFilePath)
.on('json', (jsonObj) => {
console.log(jsonObj);
jsonData = jsonObj;
})
.on('done', (error) => {
console.log('end');
}); http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, html) {
if(err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end('404 Not Found');
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(html);
return res.end();
});
}).listen(8080);
Is there a way to have the JSON Array object available when I load the HTML page and grab the object to plus into d3?
Also I tried this method but it didnt work which I open this question awhile back:
Not enough storage error when using Ajax. Large response
Thank you. I tried explaining the best i can. Please need help..

Categories

Resources