Utilize regular expressions on a JSON response dataset

Imagine a scenario where a client makes a GET request and the response is in JSON format similar to the following:

     var result = {
    "enabled": true,
    "state": "schedule",
    "schedules": [
        {
        "rule": {
        "start": "2014-06-29T12:36:26.000",
        "end": "2014-06-29T12:36:56.000",
        "recurrence": [
        "RRULE:FREQ=MINUTELY"
        ]
        },
        "wifi_state_during_rule": "disabled",
        "end_state": "enabled"
        }
    ],
    "calculated_wifi_state_now": "disabled",
    "time_of_next_state_change": [
        "2014-07-08T18:56:56.000Z",
        "2014-07-08T18:57:56.000Z"
    ]
};

This example stores the JSON response in a variable named "result". The regex expression used here is:

checkPattern = /"\w+\"(?=:)/ // Extracts all keynames "keyname": ...

The idea is to extract keynames within the object or array structure of the JSON data. Since keynames are defined as "keyname": in JSON, that's why this specific regex expression is being utilized.

Although a recursive function was considered for this task, it did not yield the desired results.

Answer №1

It's best practice to avoid using regular expressions to parse irregular structures.

Instead, extract the desired information from a parsed JSON object.
To do this, simply execute data = JSON.parse(json_string)

function getKeysRecursive(obj) {
  var result = [];
  for (var key in obj) {
    result.push(key);
    if (typeof obj[key] == 'object') {
       result = result.concat(getKeysRecursive(obj[key]));
    }
  }
  return result;
}

getKeysRecursive(({
    "enabled": true,
    "state": "schedule",
    "schedules": [
        {
        "rule": {
        "start": "2014-06-29T12:36:26.000",
        "end": "2014-06-29T12:36:56.000",
        "recurrence": [
        "RRULE:FREQ=MINUTELY"
        ]
        },
        "wifi_state_during_rule": "disabled",
        "end_state": "enabled"
        }
    ],
    "calculated_wifi_state_now": "disabled",
    "time_of_next_state_change": [
        "2014-07-08T18:56:56.000Z",
        "2014-07-08T18:57:56.000Z"
    ]
}))

// ["enabled", "state", "schedules", "0", "rule", "start", "end", "recurrence", "0", "wifi_state_during_rule", "end_state", "calculated_wifi_state_now", "time_of_next_state_change", "0", "1"]

You have the flexibility to filter, sort, and exclude numeric keys as needed.

Answer №2

You don't need to use a regular expression for this task. In JavaScript, there is a built-in function that allows you to extract the key names of an object.

For example:

Simply use Object.keys();

var data = {
    "enabled": true,
    "state": "schedule",
    "schedules": [
        {
            "rule": {
                "start": "2014-06-29T12:36:26.000",
                "end": "2014-06-29T12:36:56.000",
                "recurrence": [
                    "RRULE:FREQ=MINUTELY"
                ]
            },
            "wifi_state_during_rule": "disabled",
            "end_state": "enabled"
        }
    ],
    "calculated_wifi_state_now": "disabled",
    "time_of_next_state_change": [
        "2014-07-08T18:56:56.000Z",
        "2014-07-08T18:57:56.000Z"
    ]
};

Then, use:

console.log(Object.keys(data));

This should output:

["enabled", "state", "schedules", "calculated_wifi_state_now", "time_of_next_state_change"]

Proof: http://codepen.io/theConstructor/pen/zBpWak

Now all your object keys are neatly stored in an array.

I hope this information proves helpful to you.

Answer №3

Using this regular expression will extract all the keys from the given text:

\"(\w+)(?:\"\:)

https://regex101.com/r/eK7sF9/4

This modification allows the regex to handle multiple keys on a single line.

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

CSS2DRenderer Reset Feature

My scene, camera, renderer, and CSS2DRenderer are created using this class. I am looking for a way to reset (delete and add again) my CSS2DRenderer in order to remove any previously rendered CSS2DObject. Can you guide me on how to achieve this properly? T ...

Grab the SVG and resize it to a smaller scale

I have a small application built using Raphael.js that creates a node network with SVG and reorganizes it based on user selections. My goal is to capture the SVG image I've created and display it in a "mini-map" format at the bottom of the screen. Si ...

How can I restrict Material UI TextFields with input type = file to only allow pdf files?

Is there a way to restrict users from uploading anything other than PDF files using input type=file? I've researched about using the accept attribute but seems like it's not compatible with material UI text fields. Is there an alternative soluti ...

What is the best way to create a "tile-based board" for this game?

I am working on a project to create a board made up of tiles, but I am facing difficulty in filling up the entire board area. Currently, I have only managed to create 1 column of the board, as shown in the image. Can someone guide me on how to fill the ent ...

Occasionally, AJAX requests may not always be in the correct sequence

I'm struggling with the POST and GET requests. Everything seems to be in order on my server side until I send the data, but then things get jumbled up on the client side. For instance, the data should be received in reverse order as shown below: Data ...

Font rendering issue in Chrome extension

I have been diligently following various tutorials on incorporating a webfont into my Chrome extension, but unfortunately, none of them seem to be working for me. Despite all my efforts, the font remains unchanged and still appears as the default ugly font ...

Preventing parent requests from being triggered when a child element is clicked in Angular 2

I have a similar code structure as shown below and I am trying to achieve the behavior where clicking on the Child Div does not trigger the Parent Div click event. <div class="parentDiv" (click)="parentDiv()"> <div class="childDiv" (click)="ch ...

Is there a way to decrease a field in a MongoDB database on a daily basis?

In the process of constructing an Angular2 application using MEAN stack architecture, I have a field called Remaining Days in my MongoDB database. I am interested in having this field automatically decrement by 1 each day. Do you know if this is possible ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

How to effectively utilize multiple Vue instances in your project?

My inquiry is somewhat linked to a similar question on Stack Overflow, but I am uncertain about the level of discouragement towards the approach discussed in relation to Vue. In my situation, I am working on a project where the DOM is generated entirely b ...

Despite successful installation, node remains elusive on Ubuntu VPS

After installing node using NVM with version 0.25.0, I specifically installed node version 0.10.32. However, upon running node -v, the following error is displayed: -bash: /root/.nvm/v0.10.32/bin/node: No such file or directory Similarly, when executing ...

When the "/" button is clicked, display a menu and highlight the menu choices for selection

I have been working on developing a similar concept to Notion, and I am facing a challenge with a specific feature. I want a menu to appear when the user clicks "/", providing options to change the current block to their preferred style. Currently, I can c ...

Dependencies in Angular 2 are essential for efficient functioning

Let's examine the dependencies listed in package.json: "dependencies": { "@angular/common": "2.2.1", "@angular/compiler": "2.2.1", "@angular/core": "2.2.1", "@angular/forms": "2. ...

The drawing library (Google Maps) failed to load

I am looking to integrate drawing mode into Google Maps for my project. Below is the code snippet from my View: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <me ...

Exclude a particular row from a table when there is no identifier

My PHP code generates a basic table. <table border="1" id="control> <tbody> <tr>...</tr> <tr>...</tr> <tr>...</tr> //Row #3 <tr>...</tr> <tr>... ...

Different methods to insert data into a database without relying on mongoose

Looking for help implementing the populate() function without using mongoose within the code snippet below: ` course.students.forEach(async (student, i) => { const s = await Student.findById(student._id); console.log(s.toObject()); // ...

Shut down jquery modal

I have successfully imported Jquery Modal using the following two links (js and css) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cl ...

Transfer photos and videos to an external server using Javascript with Meteor framework

I currently have a meteor application hosted on Digital Ocean. I am considering setting up a dedicated server to store all images and videos separately from the site itself. Whenever a user uploads new media, it will be saved to this separate server. Does ...

Guide for preventing hours before the scheduled date and time with v-calendar

I am utilizing v-calendar to display the start date and time as well as end date and time in dateTime mode. My goal is to prevent the end date and time from being set before the start date and time. In order to achieve this, I have implemented the :min-dat ...

Exploring the possibilities of querying the Outlook REST API using OData

How do I incorporate search and filter into one query? String url = "https://outlook.office.com/api/v2.0/me/messages?$filter=ReceivedDateTime ge 2016-02-22&$select=Subject,From,Body,ReceivedDateTime&$search=\"subject:(Chris Brown OR Michael J ...