Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended.

<script>
abc = {
"model": {
    ...
}
}
</script>

Answer №1

A method to parse JSON is available: JSON.parse(string)

However, what has been provided is not JSON but rather a JavaScript object

abc = {
"model": {
    "DataSection": {
        "Data1": {
            "Value": "1"
        },
        "Data2": {
            "Value": "2"
        },
        "Data3": {
            "Value": "3"
        },
        "Data4": {
            "Value": "4"
        }
    }
} 
}

for (let data in abc.model.DataSection) {
  console.log(abc.model.DataSection[data].Value)
}


If the input were truly in JSON format, it would be converted as follows:

abc = `{
"model": {
    "DataSection": {
        "Data1": {
            "Value": "1"
        },
        "Data2": {
            "Value": "2"
        },
        "Data3": {
            "Value": "3"
        },
        "Data4": {
            "Value": "4"
        }
    }
} 
}`
// abc represents a string containing JSON

cde = JSON.parse(abc)
// cde is now an object based on abc



for (let data in cde.model.DataSection) {
  console.log(cde.model.DataSection[data].Value)
}

Answer №2

Instead of relying on regex, try using a more straightforward approach. In this example, I populate an array with all the values.

abc = {
  "model": {
    "DataSection": {
      "Data1": {
        "Value": "1"
      },
      "Data2": {
        "Value": "2"
      },
      "Data3": {
        "Value": "3"
      },
      "Data4": {
        "Value": "4"
      }
    }
  }
}

var array = []

$.each(abc.model.DataSection, function(index, value) {
  array.push(value.Value)
});

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

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

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

Generating a map collection from a dataset in R

I have a dataset structured like this: https://i.sstatic.net/ccUxk.png My goal is to convert this dataset into a list of maps. Here's the current code I'm using: list_tot <- list() list_tot[[1]] <- list() list_tot[[1]][['arId']] ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

I am having trouble understanding why my GraphQL query is not retrieving any data from the WordPress GraphQL API when using SWR

I have created a query to retrieve my WordPress navigation menus using the WordPress graphql plugin along with swr, graphql, graphql-request, and next.js on my local files. When I add the query on the wp-grphql section of my site, I am able to successfully ...

Locate and retrieve all the records that contain an asterisk symbol in MongoDB

Could someone provide assistance with finding documents in MongoDB that contain the '*' character using regex? For example, the following regex (db.collection.find{value: new Regex('*')}) should retrieve all documents with '*&apos ...

Struggling with the loading of intricate attribute data into an array of arrays

I am struggling with loading different data attributes into an array of arrays. I have managed to load single data attributes into the dataArray, but when it comes to the data-size which contains groups of arrays in string format, I am facing difficulties ...

Retrieving JSON data within nested structures in Go

I am encountering a recurring issue involving fetching data from nested JSON structures. The structure I am working with is outlined below, along with my attempted solution. After decoding the JSON response, I encountered an error stating "response.Result ...

Deactivate a span in real-time using ng-model

I found a helpful guide on creating a custom editable <span> using ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#example Now, I am looking to implement a feature that allows me to dynamically disable editin ...

Set tab navigation widget with a fixed height

I am struggling with setting a fixed height for my tabs widget so that when I add more content, it will display a scrollbar instead of expanding endlessly. I have checked the CSS and JS files but cannot figure it out. It is important for me to contain this ...

Is there a workaround for retrieving a value when using .css('top') in IE and Safari, which defaults to 'auto' if no explicit top value is set?

My [element] is positioned absolutely with a left property set to -9999px in the CSS. The top property has not been set intentionally to keep the element in the DOM but out of the document flow. Upon calling [element].css('top') in jQuery, Firef ...

Ways to retrieve HTML tags from a website's DOM and shadowDOM

I am currently working on a project using NodeJS where I need to extract the HTML structure of multiple websites. However, I am facing some challenges with this task. My goal is to retrieve only the HTML structure of the document without any content. It is ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

What is the best way to iterate through one level at a time?

Imagine a scenario where the structure below cannot be changed: <xml> <element name="breakfast" type="sandwich" /> <element name="lunch"> <complexType> <element name="meat" type="string" /> <element name="vegetab ...

The setting `ensureCleanSession: true` doesn't appear to be effective when included in the capabilities for Internet Explorer 11

Currently, I am testing a login/logout application with the help of protractor. One challenge I am facing is dealing with a popup that appears after each login/logout scenario. In order to ensure the popup appears after each login, I need to reset the IE ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Sorting is ineffective when employing JSON_ARRAYAGG

When I execute the following queries: SELECT name FROM customers ORDER BY name The results are displayed in alphabetical order. However, if I run this query: SELECT JSON_ARRAYAGG(name) FROM customers ORDER BY name The results come out in a specific orde ...

What is the best way to integrate Angular 5 with various sources of JavaScript code?

I am fairly new to angular. I am looking to merge an external angular script file and on-page javascript code with angular 5. I understand that angular does not typically allow for the inclusion of javascript code in html components, but I believe there m ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...