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

"Unraveling the mystery: Deserializing unidentified properties using JSON-B

Is there a way to deserialize the JSON data with dynamically generated numeric keys into a Map using Quarkus' JSON-B implementation? The challenge lies in dealing with unknown properties and mapping them to a Map<Long, MyObject> without manually ...

Is there a way to access and invoke a exposed function of a Vue component within a default slot?

Exploring the realms of a vue playground. The functions interfaceFunction in both ChildA and ChildB are exposed. In App, these functions can be called by obtaining references to the components that expose them. This allows direct function calls from with ...

JQuery does not immediately update the input value

I'm working on a jQuery placeholder that mimics the behavior of default placeholders in Chrome and Firefox for browsers that don't support it. However, I'm facing an issue where the placeholder div's HTML doesn't change as quickly ...

Separate PHP variables from a MySQL array by splitting them

I'm quite new to PHP, so bear with me if I'm posing the wrong question or inquiring about something overly basic. Within my MySQL table resides static data detailing base stats for players. My task is to exhibit each player's stats individu ...

Having trouble parsing JSON files?

Having trouble parsing JSON data and extracting the id value from a specific URL. Despite my efforts, all I get is a null value returned. var names = [String]() var SearchURL = "http://ios.khothe.vn/web/gamecards/authenticate/user/dungphiau/pass/829d8 ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

A guide on converting TypeScript to JavaScript while utilizing top-level await

Exploring the capabilities of top-level await introduced with TypeScript 3.8 in a NodeJS setting. Here's an example of TypeScript code utilizing this feature: import { getDoctorsPage } from "./utils/axios.provider"; const page = await getDo ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

Internet Explorer IE 11 encounters an "Error: Object does not support property or method" issue

Recently, I started using the jquery circleChart.min.js plugin for creating a circle chart. It's been working perfectly on all browsers except for Internet Explorer 11 (IE11). I keep getting an error message when trying to run it in IE11. Can anyone h ...

Developing a Python loop to mimic a "goto" style solution

My approach involves simulating a goto sequence. Is there a more elegant solution available? Note: The concept of storing the variables in a class variable was just for amusement (due to the .format() accessing story). n=0 while n==0: print("What is ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Notify when a certain element's ID is visible on the screen using the jQuery appear method

Having trouble getting this plugin to cooperate: https://github.com/morr/jquery.appear I attempted to reference the plugin from a CDN using Ajax: http://cdnjs.cloudflare.com/ajax/libs/jquery.appear/0.3.3/jquery.appear.js Why isn't it working as expe ...

Key to Perform Right Click

Hey, I could use a little advice window.addEventListener('keyup', function (event) { if (document.activeElement && document.activeElement.tagName === 'INPUT') { return; } switch (String.fromCharCode(event.keyCode ...

Javascript cards arranged in descending order

I'm in the process of developing a sorting feature that arranges cards in the DOM from Z to A with the click of a button. Although I've successfully implemented the logic for sorting the array, I'm facing difficulties in rendering it. Withi ...

Several DIVs with the same class can have varying CSS values

I am looking to modify the left-margin value of various separate DIVs using JavaScript. The challenge is: I only want to use a single className, and I want the margin to increase by 100px for each instance of the class. This way, instead of all the DIVs ...

Ways to retrieve a single value from a JSON object

I received the following data from my API: { "profiles":[ { "id":"d2501196e8ed4d729b3727dc64989431", "name":"infiniman" } ], "size":1 } However, I am only interested in displaying the id part. How can I achieve thi ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

Delivering compressed files in a React server

Having some trouble serving a gzip compression of my bundle.js file in React. Have tried reducing the size with uglify and dedupe, but only saw a small decrease from 2.9mb to 2.6mb. Using the compression plugin now outputs a gzip file, however, still servi ...

Empty screen appears when "npm run serve" command is executed following the build process

I am currently utilizing Material-ui. Following the project build with npm run build, I encounter a blank page when running npm run serve. I attempted to set homepage: "./" in the package.json as suggested here, however, it still displays a blank ...