Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way.

My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code snippet:

fs.readFile('./databases/' + dbName + ".json", (err, data) => {
     if (err) throw err;
     content = JSON.parse(data);
     console.log(content)
});

However, when I run this code, I only receive the entire list of members in the output:

{
  members: [
    { Username: 'User-1', Password: 'lol' },
    { Username: 'User-2', Password: 'lol' }
  ]
}

Process finished with exit code 0

Instead, what I really need is to access specific information like just the password of "User-1" from the JSON file:

{
  "members": [
    {
      "Username": "User-1",
      "Password": "lol"
    },
    {
      "Username": "User-2",
      "Password": "lol"
    }
    ]
}

(I am determined to stick to using JSON files for this project)

Any assistance on this issue would be greatly appreciated :)

Answer №1

Your inquiry lacks sufficient information


fs.readFile("./databases/" + dbName + ".json", (err, data) => {
  if (err) throw err;
  var username = "User-1";
  var password = "lol";

  for (var i = 0; i < content.members.length; i++) {
    if (
      content.members[i].Username == username &&
      content.members[i].Password == password
    ) {
      console.log("Login Successful");
      return true;
    }
  }
  console.log("Login Failed");
  return false;
});

Collect the username and password inputs from the user interface and utilize a for loop to verify if the credentials match any entries in the json database file

Answer №2

If you're considering storing data in a format similar to JSON, there are already databases available that provide excellent storage solutions such as MongoDB or Firebase.

In relation to your specific issue, the code is functioning correctly; what you need is a filter.

fs.readFile('./databases/' + dbName + ".json", (err, data) => {
    if (err) throw err;

    const username = username;
    const password = password;

    //const username = "User-2";
    //const password = "lol";

    content = JSON.parse(data);
    console.log(content.members.filter(mem => { if (mem.Username === username && mem.Password === password) return mem} ));
});

This will result in:

[ { Username: 'User-2', Password: 'lol' } ]

You'll need to incorporate a method for accepting the username and password, or any other filtering parameters you may consider.

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

Saving user input in free form within an Alexa skill Fact can be achieved by implementing the appropriate

I'm working on a skill that will allow users to send a support ticket to an office via Alexa. The user needs to provide their email, name, and issue in the message. However, I'm struggling with how to capture free-form text input and save it eith ...

Iterating through every image displayed on a webpage

Two inquiries: What is the best way to efficiently loop through every image on a specific webpage and open each one in a new browser tab? Similar concept, but instead of opening in a new tab, I am interested in substituting different images for the ...

Tips for displaying a populated ViewBag string from a try/catch block on the screen

I'm currently working on parsing a JSON file in my controller and implementing try/catch functionality for any errors that may arise. When an error occurs during the JSON parsing process, I populate ViewBag with the error message and attempt to displa ...

Exploring files within a Node.js module using npm

I'm currently in the process of developing a Node module and I want to give users the option to optionally require some files that are part of the module. For instance: var M = require('my-module'); var Foo = require('my-module/foo&apo ...

Issues encountered with sending post requests to a yii2 application when using Angular4

After implementing the following code: this.http.post('http://l.example/angular/create/', {name: 'test'}).subscribe( (response) => console.log(response), (error) => console.log(error) ); I encountered an error on ...

Tips for sending information in node.js using the content type of 'application/x-protobuf'

Having trouble sending data with content-type='application/x-protobuf'. Is it possible to request protobuf through an HTTP request? If so, how can this be achieved? ...

Express 4 compatible template engine with built-in Layouts

I'm currently exploring options other than Jade templates in express 4.x due to my dislike for Jade's syntax. EJS has caught my attention as it feels like HTML on steroids. Although Jade templates offer the great feature of using layouts, I have ...

Iterating through a dataset in JavaScript

Trying to find specific information on this particular problem has proven challenging, so I figured I would seek assistance here instead. I have a desire to create an arc between an origin and destination based on given longitude and latitude coordinates. ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

Tips for updating the CSS properties of the "html" element

html { width:100%; } Looking to dynamically update the CSS of the html tag upon button click using JavaScript. The goal is to modify the existing HTML CSS code as shown below, but achieving this dynamically with a script. Is it possible? html { w ...

React - passing down a ref as a prop isn't functioning as expected

In my current project, I am utilizing the react-mui library and aiming to incorporate a MenuList component from the MenuList composition available here. An issue arises when passing a ref as a prop down to a child component containing a menu. For reference ...

Create multiple package-lock.json files with a suffix for backup purposes

I've observed that npm generates multiple package-lock*.json files in the main directory of my project. I'm uncertain about the purpose of these files and why there are so many being created. Attached is an image displaying the generated files. ...

Sorting of dates in mui-datatables is not accurate

I have dates that are formatted using moment.js, for example ("Sat, Feb 22, 2020 12:55 PM") I retrieve them from firestore, and they appear to come in correctly as I first sort them in descending order. forms.sort(function(left, right) { return moment.u ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...

Adding data into a mysql database using PHP

Recently, I wrote some PHP code to insert form data into a table. Here's the snippet: $link = @mysql_connect("***", "***", "****"); if (!$link) { echo "save_failed"; return; } mysql_select_db("***", $link); $sql="INSERT INTO Conference (`First Na ...

Jackson Inheritance: Mapping Objects Based on Unique JSON Key Names

Here is the json structure: { "fields": [ {"expression": "count(*)"}, {"column": "field1"}, ] } To implement inheritance, classes are created as follows: @JsonTypeInfo( use = JsonTypeInfo.Id.NAME) @JsonSubTypes({ @JsonSubType ...

What is the best way to show a div after successfully sending a post value using AJAX?

How do I show this specific div after a successful AJAX post? This is what I want to display: <div class="love" id="love_0" style="border-radius: 3px; padding: 8px; border: 1px solid #ccc; right: 13px; background: #fff; top: 13px;"> <a class ...

Using handlebars to access the current URL in a NodeJS application

Looking for the most effective method to acquire the current URL in order to insert a unique ID for a div tag. Specifically working with keystone.js framework. For example, (if page == index) { "page--index-" } ...

I am interested in utilizing this callback within a function that itself contains a callback

My goal is to retrieve a list of files by using the following code snippet: var templates; db.getTemplates(function(err, reply){ templates = reply; }); However, I am encountering an error in Node.js stating "undefined is not a function". Why is the c ...