Exploring the world of JSON files using JavaScript

Basically, my bot responds to a command (!accounts) by providing users with information based on their ID. For example, if an ID of 662 sends the command !account, the bot will search for steamID 662 in the json files and display the currency and corresponding ID.

I've got that part figured out. Now, I need assistance with creating a new account in the json file if the user's ID doesn't already exist.

This is the current json code:

{
    "tradesettings": {
    "pollInterval": 5000,
    "confirmationChecker": 10000,
    "acceptEscrow": false,
    "acceptScammers": false,
    "ourmaxitems": 50,
    "theirmaxitems": 5
},

"accsettings": {
    "amountofaccounts": 3
},

"accounts":[
    { "botID":"3", "steamID":"662", "balance": 0 },
    { "botID":"2", "steamID":"211", "balance": 0 },
    { "botID":"1", "steamID":"76561198026027024x", "balance": 666 },

    { "botID":"0", "steamID":"", "balance": 0 }
]}

If I want to add an extra entry, it should look like this:

        { "botID":"4", "steamID":"421", "balance": 0 },

Resulting in:

    "accounts":[

{ "botID":"4", "steamID":"421", "balance": 0 },
{ "botID":"3", "steamID":"662", "balance": 0 },
{ "botID":"2", "steamID":"211", "balance": 0 },
{ "botID":"1", "steamID":"951", "balance": 666 },

{ "botID":"0", "steamID":"", "balance": 0 }]

How can I achieve this - creating a new account with a unique ID? By the way, my bot script is in myBot.js within the same folder as the config.json file.

Here's the code snippet for editing the configuration:

        if(ok == 1) {
        console.log("[SERVER] "+steamID.getSteamID64()+" is requesting account information.");
        for(r=0;r<= config.accsettings.amountofaccounts ;r++) {
            if (config.accounts[r].steamID != "undefined") {
                if(config.accounts[r].steamID == steamID.getSteamID64()) {
                    console.log("[SERVER] "+ steamID.getSteamID64() +" is asking for account info, responding accordingly.\n")
                    client.chatMessage(steamID.getSteamID64(), "\nDisplaying your account on this bot\nBotID: "+config.accounts[r].botID+"\nSteamID: "+config.accounts[r].steamID+"\nBalance: "+config.accounts[r].balance);

                    break;
                    ok = 0;
                    r = 0;

                }
            }
            if(r == config.accsettings.amountofaccounts) {

                console.log("[SERVER] "+steamID.getSteamID64()+" does not have an account here, creating one for them.");
                client.chatMessage(steamID.getSteamID64(),"Hold on, creating an account.\n\nDone, please type '!account' to view it\n(took 0.03 seconds)");

                //var item2={ "botID":config.accsettings.amountofaccounts+1, "steamID":steamID.getSteamID64(), "balance": 0 };
                //config.accounts.push(item2)

                config.accounts.push({botId: "10", steamID: "11", balance: 0});

                break;
                r = 0;
                ok = 0;

            }
        }
    }

There is also another file named config.json which contains the JSON data.

Answer №1

When working in node.js, it is essential to utilize the fs module for file system interactions. Here is an example of how you can use it:

const filename = `${__dirname}/config.json`;
const fs = require('fs');

let config = JSON.parse(fs.readFileSync(filename, {encoding: 'utf8'}));

// perform your operations here

fs.writeSync(filename, JSON.stringify(config), {encoding: 'utf8'});

There are a few things to keep in mind:

  1. Ensure that your file is properly formatted to prevent program crashes.
  2. Back up your config file regularly in case bad data is written by your application.
  3. Always specify explicit encodings when reading and writing files.

Answer №2

var account=[];

var item={ "botID":"3", "steamID":"662", "balance": 0 };
var item2={ "botID":"2", "steamID":"211", "balance": 0 };

account.push(item);
account.push(item2);

Below is the output :

[{ "botID":"3", "steamID":"662", "balance": 0 },
{ "botID":"2", "steamID":"211", "balance": 0 }]

If you prefer to use JSON as a map, you can follow these instructions:

var map = {};
// add an item
map[key1] = value1;
// or remove it
delete map[key1];
// or check if a key exists
key1 in map;

In order to create a new item in the JSON (Array) based on a specific field that does not exist yet, you need to iterate through the existing JSON and take action depending on the response of a function.

To locate an item by a required field (such as ID), you can utilize this function:

function findBySpecField(data, requestedField, value, responseField) {
    var container = data;
    for (var i = 0; i < container.length; i++) {
        if (container[i][requestedField] == value) {
            return(container[i][responseField]);
        }
    }
    return '';
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JSON response and service status in a WCF REST service

A WCF REST service is returning a JSON response as follows: { "categories": [{ "category_id": "10", "name": "Grocery", "freeQnty":"0", "prdcost":"100" }, { "category_id": "20", "name": "Beverages", ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Is it possible to use JavaScript to upload and manipulate multiple HTML files, replacing text within them to create new output HTML pages?

Is it possible to modify the following code to accept multiple files, process them, and then return the output? <html> <head> </head> <body> <div> <label for="text">Choose file</label> <inp ...

How can I remove ASCII characters from an ajax response?

Experimenting with the API found at , but encountered an issue with properly formatting the received string. The string looks like this: Communication that doesn&#8217;t take a chance doesn&#8217;t stand a chance. The original response includes a ...

Reactive property cannot be defined on an undefined, null, or primitive value within the context of Bootstrap Vue modal

Can someone please assist me with this error message? It says "app.js:108639 [Vue warn]: Cannot set reactive property on undefined, null, or primitive value." I encountered this error while working with a Bootstrap Vue modal. Here is a snippet of my code: ...

Getting the Correct Information from Upload Files in jQuery and PHP

While experimenting with the jquery plugin called jquery.filer, I encountered an issue during file upload on their official website . The returned value I received looked like this: { "files": [ "..\/uploads\/dK079QrL2g.docx" ], "metas": [ ...

Error in linking PHP code to display stored tweets using HTML code

![enter image description here][1]![image of output of twitter_display.php][2] //htmlsearch.html file <!doctype html> <html> <head> <title>Twitter</title> <meta charset="utf-8"> <script> window.onload = function ...

Shuffle the values of a NumPy array while keeping the largest value on the diagonal

I want to generate a square matrix using NumPy (or PyTorch) with a specific property: the diagonal elements in each row should be the largest value, while the other positions should be filled with randomly shuffled values from a given set. For instance, i ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Execute jq with the curl/bash command

I want to create a script in bash that retrieves the final URL after redirection. For example, when google.com is redirected to http://www.google.com with a status of 301, I want to capture that redirect. Here's what I have attempted so far: json=&ap ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...

Dynamically filling a second dropdown menu according to the selection made in the first dropdown using AJAX and PHP

Help! I'm feeling a bit overwhelmed. Even though this question has been answered multiple times, I still can't figure it out. There must be something so obvious that I am missing. I want the options in the second select input to be populated dyn ...

What is the best way to retrieve the value of a property within a JavaScript object?

I am facing an issue with retrieving the value of the status property from an object in my code. Below is a snippet of what I have tried: console.log("Resource.query()"); console.log(Resource.query()); console.log("Resource.query().status"); console.log(R ...

Vue.js methods bound as properties on a parent object

There are times when I come across scenarios where it would be convenient to bind methods as an object property rather than a direct Vue method. For instance, instead of: <MyInput :formatter="currencyFormat" :parser="currencyParser& ...

Tips for executing a Python function from JavaScript, receiving input from an HTML text box

Currently, I am facing an issue with passing input from an HTML text box to a JavaScript variable. Once the input is stored in the JavaScript variable, it needs to be passed to a Python function for execution. Can someone provide assistance with this pro ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Elevate state in React to modify classNames of child elements

I have a structured set of data divided into 6 columns representing each level of the hierarchy. When a user makes selections, their chosen location is highlighted with a dynamic CSS class name and displays the relevant data list. I've managed to impl ...