Attempting to utilize a prompt in order to extract and locate particular keys within a deeply nested JSON document

I'm currently facing a challenge in parsing a dynamic and complex nested JSON file. My goal is to locate a specific key within an array, but I've encountered an issue with the following snippet of code:

if (input == 'Special Weather Statement') {
        var url = "https://api.weather.gov/alerts?zone=AKZ201";
        var slide = SlidesApp.getActivePresentation().getSelection().getCurrentPage();
        var res = UrlFetchApp.fetch(url);
        var content = res.getContentText();
        var json = JSON.parse(content);
        Logger.log(json);

        
        var event = json['features']['properties']['event'];
        if (event == 'Special Weather Statement') {
          var shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 20, 259, 420, 60);
          var textRange = shape.getText();
          var description = json['features'][0]['properties']['description'];
          var description = description.replaceAll('\n',' ');
            textRange.setText(description);
            textRange.getTextStyle().setFontSize(17).setForegroundColor('#ffffff').setFontFamily("Libre Franklin");

The problem occurs in the line that reads:

"var event". If I change it to:

var event = json['features'][0]['properties']['event'];

The code only captures data from the initial block of the array, rather than conducting a comprehensive search throughout the JSON structure. I aim to scan the entire JSON file for arrays where 'event' matches 'Special Weather Statement' (or any user-specified event).

Once identified, my objective is to organize the results based on the most recent event timestamp found within the 'sent' key of that particular JSON data.

Below is a simplified representation of the JSON schema:

{
    "@context": [
     // context details reiterated here
    ],
    "type": "FeatureCollection",
    "features": [
       // detailed feature information provided here
        }
         // additional features follow

Your assistance or insights into resolving this matter would be highly appreciated. Thank you!

Answer №1

To arrange the features array in order, utilize the sort method and then extract the first element from the sorted array:

Example:
  var url = "https://api.weather.gov/alerts?zone=AKZ201";
  var res = UrlFetchApp.fetch(url);
  var content = res.getContentText();
  var json = JSON.parse(content);
  const orderedEvents = json.features.sort((a,b)=>{
    return new Date(b.properties.sent).getTime() - new Date(a.properties.sent).getTime()
  })
  console.log(orderedEvents[0].properties.event)
Resource Reference
  • Ref: Method to compare the Dates

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

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

A guide to accessing a prop from a child component in ReactJS

Currently, I am delving into React.js and experimenting with integrating the pokeAPI into a website project. One of the widgets I am working on involves displaying multiple pokemons along with their respective statistics. To achieve this, I have set up a ...

Unable to create an equilateral triangle using a two-dimensional array

As I prepare for my upcoming interview, one of the tasks is to create an equilateral triangle using a 7x7 2D array. I attempted the following code but I am unsure about how to modify it in order to successfully create an equilateral triangle. package ...

"Exploring the power of Ajax: a guide to automatically refreshing the response every

I am struggling to understand why this snippet of code isn't working as expected. The div updates when using .html, but not with my custom script. In my setup, I have two files: index.php and test.php The index file looks like this: $(document).rea ...

Steps to create a clickable image input

How can I make an image clickable in an input with type=file? <label for="formFileSm" class="label_display form-label">avatar</label> <input class="width_input mx-auto form-control form-control-sm" id="fo ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

How can I convert an HTML table into a PDF using TCPDF while ensuring that all content is contained within a single div in PHP?

I have successfully converted my JSON API data into an HTML TABLE format and now I am trying to generate a PDF from this HTML TABLE using TCPDF in PHP. Despite trying various methods related to PDF generation using TCPDF, I am facing issues with my code wh ...

Persist data in vuex with commit objects

Currently, I am attempting to retrieve objects from an axios response using the $store.commit('fetchFunction', response.data) method. I aim to access this data globally in my SPA (vue-router) by using computed in App.vue (the root component). Her ...

The regex_replace function disregards any content that follows a NULL value

Within my database table "ticket_full", there is a json type column titled "service_id" from which I want to extract data into 3 separate columns. Here is an example of the structure: [{"position":"1","typeid":"ROUTNAME&q ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

Animate failed due to the appending and adding of class

$('#clickMe').click(function() { $('#ticketsDemosss').append($('<li>').text('my li goes here')).addClass('fadeIn'); }); <link href="http://s.mlcdn.co/animate.css" rel="stylesheet"/> <script ...

Uploading multiple images with a custom meta box in Wordpress

I'm currently working on a project that involves creating a custom post type with a custom meta box. Within this meta box, I am attempting to include a media uploader for multiple images. The goal is to save multiple image IDs in an array. However, I& ...

Is it possible to display a div in front of a menu when clicking on the home, contact, blog, or services page?

Passionate Web Developer I am fascinated by the captivating effects that CSS 3D dimensions create on the screen. It feels like being immersed in a 3D realm and designing it is an exhilarating experience. I am truly enamored by this aspect of web developm ...

Engaging 3D Object with JavaScript Interactivity

I'm currently working on a project for my HCI assignment where I need to create an interactive Sphere using JavaScript. However, I am new to JavaScript and Three.js. My goal is to have the sphere display statistics of a specific subject when clicked. ...

Base adapter class returning null when displaying JSON data in list view

Hello everyone, I've encountered an issue while trying to display a list of JSON data in a ListView. I have successfully fetched the data but am struggling to append it in the list. To display the data, I created a class that extends BaseAdapter. Howe ...

A guide on transforming a JSON object representing an HTML element into a live HTML element for display on a webpage using C#, JavaScript, or jQuery

I am looking to retrieve a JSON object from a database and convert it into HTML format. Here is an example of the JSON structure: {"input":{ "name":"fname", "type":"text", "placeholder":"Ente ...

Exploring intricate nested arrays in JSON with jQuery

I have some JSON data that looks like this: { "years": [{ "id": 100531911, "year": 2012, "styles": [{ "id": 101395591, "name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)", "submodel": { ...

Learn how to use PHP's array_count_values function with an array that includes a mix of alphabet characters and integers combined

When trying to count occurrences of strings in an array using the array count function, I encountered some difficulties. It seems that the issue arises when the string contains both alphabets and digits. Is there a method to accurately count these types o ...

Discovering the minimum score in MongoDB

I have implemented a JavaScript program to find the lowest score and remove it from a collection. var types=['exam','homework','quiz'] for (student_id = 0; student_id < 800; student_id++){ for(type = 0; type < 3; ty ...

The base tag does not impact the <META HTTP-EQUIV="Refresh" element in any way

Similar Question: How to check for disabled JavaScript? I am attempting to identify whether or not JavaScript is disabled in the user's browser. To achieve this, I have inserted an iframe into the document and set it to refresh every 10 seconds. ...