Get array from a json file to a javascript array - javascript

pre-script: I'm a very noob at javascript and I'm using my c# knoledge to create a Discord bot in javascript, so I'm sorry if this question is too dumb.
I have a code to write down in a json file an array called tarefas using this code:
tarefas.push(subcomando);
bot.tarefasFile ['wait tasks'] = {
task : tarefas
}
fs.writeFile('./tarefas.json', JSON.stringify(bot.tarefasFile,null,4),
err => {
if (err) throw err;
});
cmd.channel.send('`' + subcomando + '` added to tasks.');
(subcomando is the message when someone sends w_add task_[subcomando] in my Discord server. Example below)
The output json file tarefas.json is:
{
"wait tasks": {
"tasks": []
}
For now, my code resets the value of the array tarefas when the bot restarts, so I want to reload its values from the tarefas.json file, precisely from the "tasks": [] array. How do I do that?
extra:
Example from when the json file is populated with some "tasks":
screenshot of my discord
{
"wait tasks": {
"tasks": [
"hi",
"hello",
"bye",
"math exam tomorrow"
]
}
}

Fixes by using txt file instead of json file.
write:
https://www.geeksforgeeks.org/javascript-program-to-write-data-in-a-text-file/
read:
Reading local text file into a JavaScript array
fix the split function not working:
What is causing the error `string.split is not a function`?

Related

JavaScript parsing nested JSON data

I'm creating a discord bot (using discord.js)
I'm writing a help command using pages in embeds, I have the pages working fine - however, the problem seems to come when trying to get the data from the JSON.
I have the JSON file setup in a larger config file, so it's nested inside of it.
Each command has it's name attached to it
{
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
I need to get the data from the commands area for each page.
I only have a integer input (from the page number), but I haven't got a clue how I would get the data from whatever command needs to be shown.
For something else in my project, I am using this to get the expectedArgs from the JSON object config.commands[arguments].expectedArgs, where the config is just a reference to the JSON file, this works perfectly fine. The arguments is a string input (i.e. rule), which returns whatever the info from that command.
However, would there be a way to get say the second one down (invite). I've tried config.commands[pageNumber].expectedArgs}, however, this doesn't seem to work. pageNumber would be an integer, so would it would get whatever value and then I could grab the expectedArgs.
You can get all keys from an object and select one using their index.
const json = {
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
const pageNumber = 1
// key will be a command name, e.g. 'invite'
const key = Object.keys(json.commands)[pageNumber]
const { expectedArgs } = json.commands[key]
console.log(`${key} expects ${expectedArgs}`)
Remember that indexes range starts at zero.

How to Create New Google Spreadsheet Using googleapis in Node.js

I want to create a new Google Spreadsheet using googleapis package.
Thanks to Daniel Apt's answer, I am able to create the blank file of it. But I want to give the file values.
I tried this way
const createOption = {
resource: {
properties: {
title: 'Ini judul spreadsetnya'
},
values: ['a']
}
}
But it said that Invalid JSON payload received. Unknown name "values" at 'spreadsheet': Cannot find field.. What field should I add to insert the values? And how do I create the spreadsheet in specific folder? Thank you.
What you are trying to accomplish:
You want to create a new spreadsheet with specific values.
You want this spreadsheet to be created on a specific folder on Google Drive.
Solution:
The first step to accomplish this is to understand why you can't use the values property in your request.
Looking into the documentation you can see that the request is supposed to be of an instance Spreadsheet, and this type does not contain values.
You can also see that there is no way to specify where the spreadsheet will be created, since the Spreadsheet resource does not contain any reference to it's parent folder.
If we break it down, you actually want to do three things:
Create a new spreadsheet
Move it to a specific folder
Fill it with values
Note: You can do step 1 and 2 with a single API call
Create a new spreadsheet:
Change your request body to be like the following:
const createOption = {
resource: {
properties: {
title: 'Ini judul spreadsetnya'
}
}
};
Move the spreadsheet to another folder
You will need to use the Drive API to move a file.
You do this by updating the file to have another parent. In this case, you will use the file.update call with the addParents option where you can add a comma-separated list of parentIds.
These parentIds are the Ids of the folder your file should belong to. (Yes, you can have it in multiple places).
You can extract these via API or thru the interface:
Here is how your request should look like:
const driveMoveOption = {
fileId: "", //You will insert this later
addParents: "<YOUR PARENT ID HERE>",
removeParents: "root" //To remove it from the "MyDrive" section
}
And here is a sample of how to use it:
sheets.spreadsheets.create(createOption, function (err, response) {
if (err) {
console.error(err);
return;
}
//response contains the `Spreadsheet` resource we want, with it's fileId
driveMoveOption.fileId = response.spreadsheetId; //Set the spreadsheet Id to
drive.files.update(driveMoveOption, function (err, response) {
if (err) {
console.error(err);
return;
}
//response contains the structure of a Files structure: https://developers.google.com/drive/api/v3/reference/files#resource
});
});
Creating a spreadsheet on a specific folder
If you use the Drive.files.create API instead you can use this request:
{
"mimeType": "application/vnd.google-apps.spreadsheet",
"name": "Test",
"parents": [
"<YOUR PARENT ID HERE>"
]
}
and call it with
const driveCreateAndMoveOption = {
"mimeType": "application/vnd.google-apps.spreadsheet",
"name": "Test",
"parents": [
"<YOUR PARENT ID HERE>"
]
};
drive.files.update(driveCreateAndMoveOption, function (err, response) {
if (err) {
console.error(err);
return;
}
//response contains the structure of a Files structure. Use this to get the file ID for the spreadsheet call.
});
Insert your custom values
The request to insert values on your spreadsheet should look something like this:
const appendOption = {
"spreadsheetId": "", //You will insert this later
"range": "A:A",
"valueInputOption": "USER_ENTERED",
"resource": {
"values": [
[
"a"
]
]
}
}
To use the correct SpreadsheetId you will need to run this code after you create it, and use that number.
This can be done like this:
sheets.spreadsheets.create(createOption, function (err, response) {
if (err) {
console.error(err);
return;
}
//response contains the `Spreadsheet` resource we want, with it's fileId
appendOption.spreadsheetId = response.spreadsheetId; //Set the spreadsheet Id to insert the values on.
sheets.spreadsheets.values.append(appendOption, function (err, response) {
if (err) {
console.error(err);
return;
}
//response contains the structure detailed on: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append#response-body
});
});
So as jonrsharpe's comment, finally I tried to create the blank spreadsheet and update it (there are two command call).

What is wrong with my JSON output for a Slack Message payload?

I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.

getting signature error for _POST_ORDER_FULFILLMENT_DATA_

I'm trying to post fulfillment data on SubmitFeed using javascript in sapui5 and i have done the steps as,
1) I have created json object for fulfillment data and converted it into XML again XML converted into MD5.
JSON code:-
{
"AmazonEnvelope": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "amznenvelope.xsd",
"Header": {
"DocumentVersion": "1.01",
"MerchantIdentifier": "Example"
},
"MessageType": "OrderFulfillment",
"Message": {
"MessageID": "1",
"OperationType": "Update",
"OrderFulfillment": {
"AmazonOrderID": "102-8289425-201934",
"FulfillmentDate": "2017-06-20T00:36:33-08:00",
"FulfillmentData": {
"CarrierName": "UPS",
"ShippingMethod": "Second Day",
"ShipperTrackingNumber": "1234567890"
},
"Item": {
"AmazonOrderItemCode": "1234567",
"MerchantFulfillmentItemID": "1234567",
"Quantity": "2"
}
}
}
}
};
2) Created signature as per the api documents.
3) Post the data on Feed/2009-01-01.
but i'm getting the error as:-
"<?xml version="1.0"?>
<ErrorResponse xmlns="https://mws.amazonservices.com/">
<Error>
<Type>Sender</Type>
<Code>InvalidAddress</Code>
<Message>Resource /$metadata is not found on this server. API Version is missing</Message>
</Error>
<RequestID>c00cb653-f53c-445f-9f24-82587144805d</RequestID>
</ErrorResponse>
"
Please help me to resolve this.
Thank you
The error you are getting is InvalidAddress, not a signature check error. It seems whatever you are doing in step 3 (Post the data on Feed/2009-01-01) does not work as expected. The MWS servers see a request for /$metadata instead of API name and version. Your question does not include the piece of code that does that.

Assistance needed with JSON

I'm creating a JSON file to hold information for commands.
The JSON file holds the trigger and repsonse for the commands, I have one in the file, but I want to add more, but when I do I get an error
{
"trigger": "twitter",
"repsonse": "https://www.twitter.com/Fhaelin"
}
{
"trigger": "test",
"repsonse": "This is a test command"
}
I get thrown errors and i dont know why
Here's the code I'm using to read it:
bot.on("message", function(message) {
var input = message.content.toLowerCase();
if (input === prefix + Commands.trigger)
{
bot.sendMessage(message, message.author + " : " + Commands.repsonse)
}
})
Whole code
http://hastebin.com/punabobisu.coffee
You get errors because that's an invalid JSON document. There can only be one top-level value in a JSON document.
To have a list of objects, put them in an array: [..., ...]:
[
{
"trigger": "twitter",
"response": "https://www.twitter.com/Fhaelin"
},
{
"trigger": "test",
"response": "This is a test command"
}
]
Side note: You have a consistent misspelling in your question: It's "response", not "repsonse". Only mentioning it because it'll come back to bite you at some stage if you actually put it in your code.

Categories

Resources