Extract information embedded within the script tag and separate individual elements

Having trouble extracting data from the script tag. Specifically, I need to extract the data within the jsonSwatchConfig [ ], focusing on attributes 'option_id' and 'us'.

var jar = require('request').jar();
var request = require('request').defaults({ jar: jar });
var cheerio = require("cheerio");
var cloudscraper = require('cloudscraper');
var fs = require('fs');
const logT = require('log-timestamp');
var open = require('open');
var today = new Date();
var randomsize;
var webdriver = require('selenium-webdriver');
var sizes =[];

function product() {
    // code here
}

This is the output I am currently getting:

{ "jsonSwatchConfig": 
[{"option_id":"18","us":"7","eu":"40","uk":"6","cm":"25"}, 
// more data
] }              },        
"*" : {            "Magento_Swatches/js/catalog-add-to-cart": {}        }    }

I have tried splitting and removing but unable to achieve desired results.

The source of the HTML script tag is as follows:


<script type="text/x-magento-init">
{
    "[data-role=swatch-options]": {
        // code here
        },
        "Svd_Catalog/js/svd.swatch.renderer": {
            "jsonSwatchConfig": [{"option_id":"24","us":"4","eu":"36","uk":"3","cm":"23"},{"option_id":"22","us":"5","eu":"37.5","uk":"4.5","cm":"23.5"},
            // more data
                }]      
    },
    "*" : {
        "Magento_Swatches/js/catalog-add-to-cart": {}
    }
}</script>

Looking for a secure and efficient way to extract the data. Any suggestions would be appreciated.

Answer №1

Have you thought about utilizing a RegExp? Instead of extracting data manually, this method can help streamline the process.

var pattern = /"jsonSwatchConfig": (\[.*\])/;
var results = scriptText.match(pattern)[1];

Update: In order to extract the option_id and us attributes, it is necessary to convert the string into an object first. The initial code snippet provides the array jsonSwatchConfig in string form, so to manipulate it as an array of objects, add results = JSON.parse(results). This will allow access to specific attributes like so:

results.forEach(result => {
    var x = result.option_id;
    var y = result.us;
    console.log({ x, y });
});

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

Preflight response indicates that the Access-Control-Allow-Methods does not permit the use of the PATCH method

Implementing the axios PATCH method in my ReactJS project to update a record is resulting in a failure with the following error message: Failed to load : Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response. Below is the co ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

A simple method to obtain the ID of the element that has been clicked and save it in a variable to be utilized in a function responsible for

Seeking assistance in optimizing the code below by removing the specific #static id and allowing for dynamic IDs such as #dynamic within the one click function. This would eliminate the need to repeatedly copy and paste the same function with different ID ...

Switch out external CSS stylesheets automatically using toggle scripting

Hello there! I've been trying to figure out a way for this script to switch back to the original CSS external stylesheet. Here is the code that I currently have: $(document).ready(function() { $("#css-master2").click(function() { $("link[title=chang ...

Achieving a stacked layout for a JavaScript menu that is responsive and positioned below an

Despite several attempts, I am struggling with a problem and now need some help. I have designed a menu system with a logo, but the issue is that the menu does not stack under the logo when @media reaches 823px. Can anyone suggest a solution to this proble ...

When a dropdown list only contains one item, the jQuery change event does not get triggered

I'm currently exploring ways to trigger events when options in a dropdown menu are clicked. I haven't come across any clear explanations on how to achieve this. What I specifically need is to activate the event and utilize the selected value. Usi ...

What is the best way to locate the nearest marker using the Google Maps Direction Service?

Currently, I am engaged in the development of a Google Maps project where I am integrating markers retrieved from a database onto the map using the drawMarkers function. In addition to this, the Google Maps feature tracks your current location and refreshe ...

Null reference exception in Typescript + NextJS

I am facing an issue where the ref to a custom child component in my parent component is always null, preventing me from calling methods on it. Even though I believe I have implemented everything correctly, the ref (named CanvasUI) remains null and I can& ...

Utilize JavaScript to parse JSON containing multiple object settings

After receiving the server's response, I am looking to extract the "result" from the JSON data provided. This is my JSON Input: { "header":{ "type":"esummary", "version":"0.3" }, "result":{ "28885854":{ "uid":"28885854", "pub ...

Incorrect JSON data population issue

I have successfully populated data from the test2 JSON file. However, my goal is to click on a table entry and display relevant charges for that customer in a div table. Currently, all I see is: Account Chargecode Rate {{ x.Customer ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

Submit your document using the connect-form tool

I ran into an issue while trying to upload a file using connect-form. I found that in order to successfully upload the file, I had to disable the bodyParser() function in my app.js. If I kept bodyParser() enabled, it would result in an error: loading forev ...

Setting up SUID sandbox properly for Docker/Selenium with Headless Chrome

I am experimenting with running Selenium and headless Chrome in a Docker container for testing purposes. Previously, I successfully ran Selenium in headless Chrome outside of my Docker container using the code snippet below in my .js file: const client = ...

Calculate the total number of blank input boxes within a specific row of the table

What is the method to count the number of input boxes without a value in a table row using jquery? For instance: <table id="table1"> <tr class="data" id="row5"> <td><input type="text" value="20%" /></td> <td><input ...

Creating a personalized audio player using HTML

I have created a design for an audio player that I would like to implement using the HTML audio player element. https://i.sstatic.net/vJpGg.jpg When I tried <audio></audio>, it just displayed the default player: https://i.sstatic.net/nyNj8.j ...

Is there a way to make images appear on the screen only when they come into view on

While exploring the internet, I came across something quite intriguing on a website: As you scroll down the page, images only load when they come into view in the browser window. This is a feature I have never seen before and I am curious if anyone else h ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

Modify the div's max-width attribute based on checkbox selection in HTML

There is a coding challenge involving a checkbox and a div. When the checkbox is checked, the max-width attribute of the div should decrease (causing it to shrink in size), and vice versa. function adjustTableWidth(checkbox) { var table = document. ...

What is the process for removing a row from the database in this scenario?

My current goal is to implement a functionality where clicking on the "Delete" button will remove a file from the server and also delete the corresponding database entry with the same file name. The file deletion process on the server works perfectly, but ...

Stop all child components in React from mounting when the page loads

I am currently working on a single-page React application where I need to mount specific components at different times. However, all the components are loading simultaneously instead of one at a time. In my research on StackOverflow, I came across solutio ...