What is the best way to connect to a JSON key that is consistently returned with a varying or unpredictable name?

I am currently working on an Angular 4.x application where my goal is to showcase a random Wikipedia article. Each time I check the JSON data in Chrome Dev Tools under query/pages, I notice that the pageID always has a different number. The structure of the response is a JSON object rather than an array, with a dynamically named property which makes it challenging for me to create a TypeScript interface or bind to it. Any suggestions on how I can approach this issue?

Here's an example of the JSON response from the Wikipedia API:

{
  "batchcomplete": "",
  "continue": {
    "grncontinue": "0.241230031087|0.241230543855|19422120|0",
    "continue": "grncontinue||"
  },
  "warnings": {
    "extracts": {
      "*": "\"exlimit\" was too large for a whole article extracts request, lowered to 1."
    }
  },
  "query": {
    "pages": {
      "742585": {
        "pageid": 742585,
        "ns": 0,
        "title": "Speedway",
        "extract": "<p><b>Speedway</b> may refer to:</p>\n<h2><span id=\"In_racing\">In racing</span></h2>\n<ul><li>Oval track racing, motor racing on an oval track which turns in one direction</li>\n<li>Cycle speedway, a form of bicycle racing</li>\n<li>Motorcycle speedway, a form of motorcycle sport</li>\n<li>Dirt track racing, known as speedway in Australia and New Zealand</li>\n</ul><h2><span id=\"Other_uses\">Other uses</span></h2>\n<dl><dt>Placenames</dt>\n</dl><ul><li>Speedway, California, former town in Butte County</li>..."
      }
    }
  }
}

Answer №1

Utilize the Object.keys method to extract the keys from an object as an array.

var data = {
  "batchcomplete": "",
  "continue": {
    "grncontinue": "0.241230031087|0.241230543855|19422120|0",
    "continue": "grncontinue||"
  },
  "warnings": {
    "extracts": {
      "*": "\"exlimit\" was too large for a whole article extracts request, lowered to 1."
    }
  },
  "query": {
    "pages": {
      "742585": {
        "pageid": 742585,
        "ns": 0,
        "title": "Speedway",
        "extract": "<p><b>Speedway</b> may refer to:</p>\n<h2><span id=\"In_racing\">In racing</span></h2>\n<ul><li>Oval track racing, motor racing on an oval track which turns in one direction</li>\n<li>Cycle speedway, a form of bicycle racing</li>\n<li>Motorcycle speedway, a form of motorcycle sport</li>\n<li>Dirt track racing, known as speedway in Australia and New Zealand</li>\n</ul><h2><span id=\"Other_uses\">Other uses</span></h2>\n<dl><dt>Placenames</dt>\n</dl><ul><li>Speedway, California, former town in Butte County</li>..."
      }
    }
  }
};

var MyArray = Object.keys(data.query.pages);

console.log('MyArray: '+ JSON.stringify(MyArray));

// Accessing Required Data

console.log('Page ID: '+ data.query.pages[MyArray[0]].pageid)

Answer №2

To access a specific page number from an object in javascript, you can utilize the Object.keys method as shown below:

var obj={
  "batchcomplete": "",
  "continue": {
    "grncontinue": "0.241230031087|0.241230543855|19422120|0",
    "continue": "grncontinue||"
  },
  "warnings": {
    "extracts": {
      "*": "\"exlimit\" was too large for a whole article extracts request, lowered to 1."
    }
  },
  "query": {
    "pages": {
      "742585": {
        "pageid": 742585,
        "ns": 0,
        "title": "Speedway",
        "extract": "<p><b>Speedway</b> may refer to:</p>\n<h2><span id=\"In_racing\">In racing</span></h2>\n<ul><li>Oval track racing, motor racing on an oval track which turns in one direction</li>\n<li>Cycle speedway, a form of bicycle racing</li>\n<li>Motorcycle speedway, a form of motorcycle sport</li>\n<li>Dirt track racing, known as speedway in Australia and New Zealand</li>\n</ul><h2><span id=\"Other_uses\">Other uses</span></h2>\n<dl><dt>Placenames</dt>\n</dl><ul><li>Speedway, California, former town in Butte County</li>..."
      }
    }
  }
}

var pageNo=Object.keys(obj.query.pages)[0];

console.log(pageNo)

Answer №3

To implement formatversion=2:

action=query&format=json&prop=extracts&exlimit=1&generator=random&formatversion=2

{
    "batchcomplete": true,
    "continue": {
        "grncontinue": "0.452345678901|0.452345678902|12345678|0",
        "continue": "grncontinue||"
    },
    "query": {
        "pages": [
            {
                "pageid": 23456789,
                "ns": 0,
                "title": "Sample Village",
                "extract": "<p><b>Sample Village</b> is a fictional village located in the land of imagination. It is known for its scenic beauty and peaceful surroundings, making it a popular destination for tourists looking to unwind and relax.</p>\n<p>The population of Sample Village fluctuates depending on the season, with an average of 50 residents throughout the year.</p>"
            }
        ]
    }
}

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

Using Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Whenever I press a button, my desire is for each picture to seamlessly reposition itself in the exact same spot on the screen

Having some issues with my code. When I click a button, the plan is for the pictures to change one by one to simulate a traffic light sequence. However, when I run the code, all the pictures appear at once without any effect from the button. Any help in ac ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

Transferring the value of a variable from Block to Global Scope in FIRESTORE

I'm currently working on an App in Firebase, utilizing FireStore as my primary Database. Below is a snippet of code where I define a variable order and set it to a value of 1. Afterwards, I update the value to 4 and use console.log to verify. Everyt ...

Encountering a ReferenceError while attempting to implement logic on a newly created page

I've been experimenting with building a website using the Fresh framework. My goal was to add a simple drop-down feature for a button within a navigation bar, but I'm struggling to figure out where to place the necessary code. I attempted creatin ...

Strategies for retaining additional fields added via JavaScript when the page is refreshed

var newField = document.createElement("lastExp"); newField.innerHTML = 'insert new form field HTML code here'; document.getElementById("lastExp").appendChild(newField); I have a button that adds an additional form field with a simple click. ...

executing the following event in Node.js

Is it feasible to execute only a portion of the code on each iteration of the event loop in an application where requests can take a second or two? Consider the following scenario: function foo() { ...critical code... ...start processing the next ...

What is the method for attaching a keypress event to an HTML document?

Looking to add an interactive touch to my website by creating a "press any key" page. When a key is pressed, I want it to kick off animations that bring the page to life - like sliding elements in from different directions. Open to using jQuery or plain ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

What methods and applications are available for utilizing the AbortController feature within Next.js?

My search application provides real-time suggestions as users type in the search box. I utilize 'fetch' to retrieve these suggestions from an API with each character input by the user. However, there is a challenge when users quickly complete the ...

Angular (4, 5, 6, 7) - An easy guide to implementing slide in and out animations using ngIf

How can you implement a basic sliding animation in Angular4 to show and hide a container element? For example: <div *ngIf="show"> <!-- Content --> </div> Slide the content in (similar to jQuery's slideDown() method) from top t ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

Leveraging Amplify for offline storage while transitioning between HTTP and HTTPS protocols

Recently, I encountered an issue with Amplify 1.0a1 on my website. It seems that when storing the value of prod_id in localStorage on a page using HTTP, and then navigating to a page using HTTPS (such as the 'list' page), I am unable to access th ...

Verify in JavaScript if the script is executing within a WinStore (WinJS) program

I am in the process of developing a JavaScript library that is compatible with both Windows Store (WinJS) applications and traditional HTML/JavaScript apps. The dependency I am utilizing loads dynamically and has separate SDKs for WinJS apps and standard w ...

Transfer files with Ajax without the need for a form tag or submission

I'm trying to send images via AJAX without submitting a form. Normally, when submitting a form I can access the images using $_FILES['images']['tmp_name']; However, when trying to send files, I receive an object FileList in an arra ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...