Navigating to JSON input in Express correctly

I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded)

[{
  "ID": "1",
  "NAME": "George Washington",
  "PAGE": "http://en.wikipedia.org/wiki/George_Washington",
  "DATE1": "30/04/1789",
  "DATE2": "4/03/1797",
  "PARTY": "Independent ",
  "IMG": "GeorgeWashington.jpg",
  "THUMB": "thmb_GeorgeWashington.jpg",
  "HOMESTATE": "Virginia"
}

Below is a snippet from my index.js for handling Express routing:

var express = require('express');
var app = express();

app.set('port', process.env.PORT || 3000);

var myData = require('./data.json');

app.get('/api', function(req, res){
res.json(myData);
});

app.get('/api/:id', function(req, res){
  res.json(myData[req.params.id]);
  });

While a call to /api returns the entire dataset and /api/1 fetches the first entry, I aim to create another route that allows users to access specific elements within the JSON. For instance, calling

https//<blah>/api/1/HOMESTATE

should return

"HOMESTATE": "Virginia"

Is it possible to achieve this using parameters or do I need to iterate through the JSON based on the provided ID? Any guidance with code examples would be highly appreciated.

Answer №1

One way to achieve this is by utilizing route parameters.

app.get('/api/:id/:property', function(req, res){
  var response = {};
  response[req.params.property] = myData[req.params.id][req.params.property]
  res.json(response);
});

To enhance the stability of your application, it is recommended to implement error handling to handle invalid route parameters and prevent crashes.

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

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

Issues with clicking in JS eventListener

I'm in need of some assistance with a small header issue in my project. I've included all the necessary header files so that you can run it in a snippet and see what's going on. The problem lies within my JS file. When running the file, you ...

Toggle the checkbox to either select or deselect the value

I am attempting to toggle the value of a checkbox. When checked, the value should be set to active, and when unchecked, it should be set to disabled. The current code successfully changes text based on the checkbox status, but the issue is that the value ...

Creating a Custom FlatList Content Container with React Native

Is it possible to customize FlatList items with a custom component? I want to create a setup where my FlatList items are encapsulated within a custom component similar to the following: <ScrollView pt={8} px={16} pb={128} > <Card e ...

Divide the string into segments and set up pagination

<div><p class="pagi">page 1 content</p><p class="pagi">page 2 content</p><p class="pagi">page 3 content</p></div> I am currently facing a challenge with the string provided above. I need to create pagination ...

What is the mechanism behind pushing an empty array into another empty array?

let arr = []; console.log(arr.push([])); // 1 Instead of logging [[]], the output is 1. Can someone explain what is happening in the code above? ...

Unable to arrange an array of JavaScript objects retrieved via an Angular REST request

I'm currently encountering an unusual issue with sorting an array of JavaScript objects. While sorting some dummy data works fine, I am unable to sort the array when fetching the object through an Angular REST call. The structure of the message is as ...

What is the reason behind the ineffectiveness of the given middleware syntax in Express?

Here is the example I'm referring to: https://github.com/jaredhanson/passport-local/blob/master/examples/login/app.js This specific piece of code is what caught my attention: app.post('/login', passport.authenticate('local', ...

In need of styling text using CSS?

Despite setting the CSS to .text { word-wrap : break-word; max-width: 100px}, the text is not wrapping as expected. It is still displaying in a single line. I am anticipating that the large text should wrap onto the next lines. ...

Searching for a Value in a Python Dictionary: A Beginner's Guide

Currently, I am in the process of downloading Yahoo Finance statistics data which results in a Python nested dictionary structure. My primary goal is to locate 'enterpriseValue' and 'trailingPE' within this nested dictionary. One of th ...

Protecting a javascript string in php: A comprehensive guide

Having trouble with my PHP javascript string. Attempted to add a string to a variable within a switch statement but encountered an error: $blocPub = '<script type="text/javascript"> var rdads=new String(Math.random()).substring (2, 11 ...

socket.io, along with their supporting servers

Can socket.io function separately from being the webserver? I prefer to utilize an external webserver, but in order for it to function properly I require /socket.io/socket.io.js. Is there a method other than duplicating[1] this file? I want to avoid comp ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

Issue with content overlapping when hamburger icon is tapped on mobile device

When the hamburger menu is pressed on smaller screens, I want my navbar to cover the entire screen. To achieve this, I included the .push class in my code (see the jQuery and CSS) to trigger when the .navbar-toggle-icon is pushed. However, after implemen ...

Access the JavaScript variable in a webview and store it in an Android variable

I have been attempting to retrieve a variable from a webview, but I am only able to make modifications like this: browser.loadUrl("javascript:var x = document.getElementById('login').value = 'something';"); However, I need to be able ...

Convert form data into JSON format while maintaining numerical values

One question that is frequently asked, but I have yet to find a solution for, is how to create a JSON body from a form in which the quotes are placed around the property names rather than the values. The desired JSON body should look like this: { "salary1 ...

How can we ensure that the Material-UI <Select> component is as wide as the widest <MenuItem>?

I am attempting to adjust a Mui Select field so that it is the same width as its largest MenuItem. Despite trying to utilize the autoWidth prop on the Select component, I have not been able to achieve the desired result. To better illustrate the issue, I h ...

Creating a SQL table in Python that can be converted to a JSON object with

Hey there! I need some help converting a SQL query into JSON using Python. I'm running into an issue when trying to use a parameter in the SQL query: Error message: sql syntax error: incorrect syntax near "%" https://i.sstatic.net/1UF8U.png The que ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...