Is it possible to utilize the Substring() method on JSON data retrieved from an API?

I have been working with a timezone API that provides the time from a specific city in this format: 2019-10-26 15:30. I want to display only the time on my page, but currently it shows the full date as well, which is not what I desire.

This is my first experience dealing with APIs and JSON. After searching and googling for solutions, I still haven't found a straightforward fix.

The fetched data displays the whole date, and I attempted to use substring to get only the time part, but it didn't work as expected. However, I am unsure if the returned data is even a string to begin with.

Here's an excerpt of my code:

let newYorkClock = document.getElementById("nyClock");

function displayTime() {
   fetch("http://api.geonames.org/timezoneJSON?lat=40.7&lng=-74&username=demo")
    .then(response => {
      return response.json();
   })
    .then(data => {
      var timeString = data.time;
      timeString.substring(11);

      newYorkClock.innerHTML = timeString;
   });
}

displayTime();

I'm curious about what exactly gets returned when fetching data from an API.

Is there a way to extract or manipulate only a portion of the retrieved data from an API? If so, how can this be achieved? This is my first time asking a question rather than solely relying on Google for answers.

Answer №1

The issue with the example you provided is due to the behavior of the substring() method in JavaScript. This method extracts characters from a string based on specified indices and creates a new substring rather than updating the original object.

  var timeString = data.time.substring(0, 11);

  newYorkClock.innerHTML = timeString;

If you want to modify the original string similar to your approach, you can do the following:

  var timeString = data.time;
  timeString = timeString.substring(0, 11);

  newYorkClock.innerHTML = timeString;

Additionally, you may find using the debugger statement or console.log() helpful for debugging your code: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger

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

Error encountered in Express.js blogging app: Issue arises when attempting to filter posts by category, resulting in a "Cast to ObjectId failed" error

Currently, I am developing a blogging application using technologies like Express, EJS, and MongoDB. In the application, I have structured posts into different categories, each stored in its own collection. However, I encountered an issue while attemptin ...

What is the best way to retrieve local variables within a React function?

I keep encountering this issue where I get a TypeError saying that the property 'classList' cannot be read for an undefined value, and this error occurs even before the functions are executed. The specific line causing the error is slide[n].class ...

When the user clicks on an element, my JavaScript code dynamically updates the CSS property by changing the window

When a tag is clicked in HTML triggering an onclick event, the CSS property that was updated in the JavaScript does not persist. The changes appear momentarily and then disappear once the window is refreshed. Javascript: <script type="text/javascript"& ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

Troubleshooting a JSON nesting issue in AWS Athena

I am facing an issue with a nested JSON file structure which is as follows: \n \"total\" : 510,\n \"start\" : 0,\n \"count\" : 500,\n \"data\" : [ {\n \"id\" : 294,\n ...

What is the process for transferring data between components in React?

Currently, I have set up a system to display an employee table from the database. Each record in the table includes an "edit" link which, when clicked, should trigger the display of a form below the table containing the corresponding records for editing. T ...

Using ES6 Classes to map an array of variables

If I have a list of 5 people's names, such as Sam, Ash, Moe, Billy, Kenzi, and want each name to have properties like doneHomework and lazy using a class: class Person { constructor() { this.doneHomeWork = 0; this.lazy = false; ...

Show the output of a MySQL query on a modal, alert, or popup box within a webpage initiated by a search box, with the option to close the

Having worked in IT for 16 years, I am new to coding and seeking help on displaying search results from an input HTML box. I want the data from a MySQL database to be displayed in a modal, alert, or popup box with a closing "X" button. This database only c ...

Validation failure occurring due to JSON Schema - The error does not match the expected 'object' type

I've been experimenting with the jsonschema and python_jsonschema_objects libraries to generate a Python object from a schema file, populate it with data, and then verify it against the original schema. It seems like I might be missing something in my ...

A sleek Javascript gallery similar to fancybox

I'm currently working on creating my own custom image gallery, inspired by fancybox. To view the progress so far, please visit: I've encountered some issues with the fade effects of #gallery. Sometimes the background (#gallery) fades out before ...

Angular Display of Scrolling Feature not Functioning Properly

After clicking on show5 and then goto5, everything functions as expected. However, when clicking on showngo5, it does not work as anticipated, despite the fact that the same methods are being called. What is causing showngo5 to not work in this plunker h ...

Event emitting from a parent Vue.js component

I can't figure out why my code is not functioning properly. I have an event called 'leave' that should be triggered on blur. The components show up correctly, but the event doesn't fire when leaving the inputs. Vue.component('te ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

Numerous animated elements within A-frame

Is there a way to incorporate animation into an A-Frame glTF model, causing it to smoothly move 5 spaces to the left and then 5 spaces forward? Below is my current code: <a-gltf-model color="#FFFFFF" width="1" height="1" de ...

Error: The index $_GET[...] is not defined

When transferring a javascript variable to a php file, I encounter an issue where $_GET['something'] keeps returning as an undefined index. Despite this error, the correct result is displayed and written into the xml. However, when I attempt to ...

Script function in Google Sheets HTML not being called

Within my Google app, I have the following HTML code that is supposed to call a function below. However, I am not getting any response. This script has been used consistently throughout my code until now. <div id= "right_column"> <p> ...

Using AJAX to send data from knockout observables to the server in JSON format

I'm currently facing an issue where I am trying to send form fields that are linked to specific observables to my server as a JSON object, but I keep receiving an empty JSON string on the server side. I want to avoid sending the entire view model just ...

Achieving 10 touchdowns within a set of 5 plays during a football game

Receiving a page from an external site where I have no control. The table structure is as follows: <table><tbody> <!-- headers --> <tr><td></td> <td></td> <td></td> <td>< ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

Encountering a 404 error when typing a link and refreshing the page in Laravel combined with VueJS

I encountered an issue while working on a Laravel VueJS application for our Proof of Concept (POC). I have integrated vue-router into the project and it is functional. However, whenever I attempt to navigate to a specific page defined in the routes of app. ...