Extract data from the DOM in JSON format

Upon pressing Ctrl+U, I discovered the following JSON in the DOM of my page:

<script type="text/x-magento-init">
{
  "#country": {
    "regionUpdater": {
      "optionalRegionAllowed": true,
      "regionListId": "#region_id",
      "regionInputId": "#region",
      "postcodeId": "#zip",
      "form": "#form-validate",
      "regionJson": {
        "config": {
          "show_all_regions": true,
          "regions_required": [
            "AU",
            "BR",
            "CA",
            "CN",
            "CO",
            "HR",
            "EE",
            "IN",
            "LV",
            "LT",
            "MX",
            "PL",
            "RO",
            "ES",
            "CH",
            "US"
          ]
        }
      }
    }
  }
}
</script>

I am seeking guidance on how to extract the value of regionJson from this script within my custom JavaScript file. Any suggestions or solutions would be greatly appreciated.

Answer №1

Here's a different approach to handle the JSON data without using # in key names.

First, I used the replace method to remove the # symbol and then parsed the data.

 var getTxt=$('#script').html().replace('#country','country');
 var jsonData= JSON.parse(getTxt);
  
 console.log(jsonData.country.regionUpdater.regionJson);

Check out the Working Demo here

Answer №2

To retrieve the regionJson data, use the following method:

jsonData = {
  "country": {
    "regionUpdater": {
      "optionalRegionAllowed": true,
      "regionListId": "#region_id",
      "regionInputId": "#region",
      "postcodeId": "#zip",
      "form": "#form-validate",
      "regionJson": {
        "config": {
          "show_all_regions": true,
          "regions_required": [
            "AU",
            "BR",
            "CA",
            "CN",
            "CO",
            "HR",
            "EE",
            "IN",
            "LV",
            "LT",
            "MX",
            "PL",
            "RO",
            "ES",
            "CH",
            "US"
          ]
        }
      }
    }
  }
}

console.log(jsonData["#country"]["regionUpdater"]["regionJson"])

Answer №3

To tackle this issue, it is advisable to locate the phtml file that could be making calls to blocks or functions supplying the regionJson data. You can access this data in your JS file by invoking it through text/x-magento-init and providing the same configuration as mentioned in your query. Another option is to store the data in the global JavaScript object window for easy retrieval at a later point within the JS file.

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

Unveiling the Magic of Django's Ajax Model Form

I am working with two models in my Django project: class Exercise(models.Model): text = models.TextField() class Score(models.Model): user = models.ForeignKey(User) exercise = models.ForeignKey(Exercise) score = models.IntegerField() class Meta ...

Looking at and adding to JSON files in Python

These are the contents of my two files: file1.json [ { "name": "john", "version": "0.0" }, { "name": "peter", "version": "1.0" }, { "name&qu ...

Navigating through objects within arrays within objects in Angular

I seem to be encountering some difficulty in displaying data from an API call on Mapbox. Only one marker is showing up on the map instead of the expected 10 markers. I suspect there might be an issue with my ng-repeat implementation, but I can't pinpo ...

Fixing a menu hover appearance

I recently encountered a small issue with the menu on my website. When hovering over a menu item, a sub-menu should appear. However, there seems to be a slight misalignment where the submenu appears a few pixels below the actual menu item. Check out the w ...

Semantic UI Troubles: Unraveling the Sidebars and #pusher Defects

Hey there, I could really use some assistance with an issue I'm facing. I have this particular structure that's causing me trouble. <div id="toolbar" class="toolbar overlay-displace-top clearfix toolbar-processed"> ... </div> < ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

Retrieve the initial key from an object in javascript

Though seemingly simple, I'm stuck on finding the solution: Within my jquery object (displayed in console.log): { id_ship: "1", id_company: "1", code: "DE", // other properties... } My goal is to extract the first key from th ...

The resume button is failing to activate any functions

I recently encountered an issue with a JS file that is associated with a Wordpress Plugin, specifically a Quiz plugin featuring a timer. I successfully added a Pause and resume button to the quiz, which effectively pauses and resumes the timer. However, I ...

Utilizing JSON and forms within Visual Studio environment for seamless development

When I work on Visual Studio and create a form, the common language RunTime Support automatically changes to /clr. However, when I try to add json libraries, I encounter the following error: is not supported when compiling with /clr or /clr:pure Switc ...

The process of retrieving data from a dropdown list and populating checkboxes using Ajax/Jquery

I'm looking for a way to dynamically retrieve data in checkboxes based on a selected user from a dropdown list. The dropdown list contains users, and the checkboxes display pages data. Assuming we have a table called user with columns user_id and use ...

Utilize the IFRAME element in jQuery/PHP to reference a specific TAG within a URL

Is it possible to link to a specific tag (such as H1) within an iframe using the source URL? For instance, consider the link . I am wondering if it's feasible to refer to the first H1 element in the provided link ("How the Fed rate hike will impact ...

Elegant Modal Form Submission Using jQuery

Having trouble submitting a modal jQuery form? A code snippet was borrowed from a website with minor modifications and the JavaScript was moved to a separate file. The challenge lies in transmitting form data to a PHP script via AJAX. The serializedArray() ...

Rotating Image Sub Menu Using HTML, CSS, and jQuery

I'm currently working on a project that involves creating a sub menu with interactive image displays. The goal is to have an image appear when hovering over an li tag. Here is an example of what I'm aiming for: If you'd like to see it in a ...

Rails controller did not receive the Ajax call

I have noticed that when I make an Ajax call using jQuery, the data is always transmitted (status 200), but there are times when it's not properly received by the Rails controller. The data is sent correctly, but most of the time the controller respon ...

Looking for matching index in rotated array

Currently, I am working on a design with a reference rectangle (colored in red). Within a rotated container div (#map), I am trying to create a duplicate rectangle (in yellow) that matches the size and position of the original "base" rectangle, regardless ...

How to implement a Datapicker plugin in jQuery version 2.1.1?

After discovering a datepicker plugin designed for JQuery version 1.1.1, I encountered compatibility issues with my current version of 2.1.1. Does anyone know if there is a datepicker plugin available specifically for jQuery 2.1.1? ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

Ways to categorize JSON information

Is it possible to group JSON data by group_name? JSON : [ {"fullname":"fffffffff","email":"sss@gg","mobile":"3333333333","designation":"ggg","group_name":"engineers"}, {"fullname":"ddddddddddd","email":"sssg@gg","mobile":"3333333333","designation":"ffff ...

Implementing jQuery - I Require Sequential Execution of Functions

I have a unique scenario where I need to ensure that two jQuery functions run in sequence when a form is submitted. The first function performs an AJAX call to check the database for any duplicate values and returns a response. It is crucial that the sec ...

Using jQuery to set the background-image on the body's after pseudo-element with CSS

I am currently utilizing body:after for setting the page wallpaper. body:after { background-image: url('assets/img/wallpapers/<?php echo $getWallpaperFile; ?>'); } CSS content: ' '; display: block; position: absolute; left: ...