Transforming a string into JSON with proper sanitization

When web scraping, the website returns a string like this on get request:

jQuery18305426675335038453_1429531451051({"d":[{"__metadata":"cool"}]})

The complete code snippet is provided below:

var baseUrl = "http://SOMEURL.COM?spatialFilter=nearby(52.47952651977539,-1.911009430885315,400)&$select=*&$top=200&$format=json&key=AjF8l9J6TH-WM5tkfFYdYE8NVUx9SFe4ya9aBaxKFFPBImvFWWHPOsRMSBesWblU&jsonp=jQuery18305426675335038453_1429531451051&_=1429532300821%20HTTP/1.1";

var casper = require('casper').create({
    verbose: false,
    logLevel: 'debug',
    pageSettings: {
        loadImages:  false,
        loadPlugins: false
        }
});


var fs = require('fs'),
    shopInfo,
    savePath, 
    date = new Date(),
    secondsNow = date.getSeconds(),
    day = date.getDate(),
    minute = date.getMinutes();
    month = date.getMonth() + 1, 
    fname = 'virginmedia-'+month+'-'+day+'-'+minute+'-'+secondsNow+'.txt';

function saveToFile(finalData) {
    savePath = fs.pathJoin(fs.workingDirectory,
     'output',fname);
    fs.write(savePath, finalData, 'w');

}


casper.start(baseUrl, {
            method: 'get',
            headers: {
            'Accept': 'application/json'
                    }});
casper.then(function getData(){


    var rawData = this.getPageContent();

    shopInfo = rawData;
        shopInfo = shopInfo.replace("jQuery18305426675335038453_1429531451051(",'');
        shopInfo = shopInfo.replace(/\)$/,'');
        shopInfo = JSON.parse(shopInfo);
    var resultPack = shopInfo.d.results;

    var finalData = resultPack.map(function(val){
    return [
              val.Latitude,
              val.Longitude,
              val.EntityStoreName
           ];
    });

    saveToFile(JSON.stringify(finalData)); 
    casper.echo("\n Hello! I just returned " + finalData.length
    + " shops");

});
casper.run();

In essence, it's valid json inside a function call structure. However, I specifically need the JSON part extracted.

If within a browser environment, I could easily create a function with the same name that would return its own parameters:

function jQuery18305426675335038453_1429531451051() {
  return arguments[0];

}

Unfortunately, in casperjs, this approach doesn't seem to work. So, my workaround was using regex to extract the JSON string:

shopInfo = shopInfo.replace("jQuery18305426675335038453_1429531451051(",'');
shopInfo = shopInfo.replace(/\)$/,'');

I'm curious if there is a better way to achieve this?

Edit 1 : According to comments, it appears that it's JSONP rather than JSON which simplifies things. I found a solution after researching about JSONP here.

Edit 2 : Another suggestion from the comments indicated that by modifying the request, the website can directly return proper JSON data!

Answer №1

Upon reviewing the feedback, I have the solution:

  1. The specific format is known as JSONP, or JSON with padding. More information can be found on this topic in this post

  2. It is possible to avoid using JSONP by adjusting the HTTP request to return authentic JSON data. Simply eliminate this section from the request:

    jsonp=jQuery18305426675335038453_1429531451051&_=1429532300821%20HTTP/1.1

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

Mastering Backbone views and router functionality is essential for building scalable and efficient web

In my code, I have a series of page states that mimic the steps of a shopping cart checkout process. The first set of code sets up the ItemsCollection, ItemsView, and ItemsApp in Backbone.js. var ItemsCollection = Backbone.Collection.extend({ model: I ...

IsContainer and IsModel properties in Dragular are not functioning properly with the accept or canBeAccepted methods

Scenario 1 : Let's consider using two containers, named A (Drag Source) and B (Drop Source). Code snippet : dragularService(containerLeft, { containersModel: [DragularconTainer], copy: true, canBeAccepted: function(el, source) { ...

Are there any ways to pass an onClick function to a controller in React?

To prevent duplicate numbers from being generated, I added a button that, when clicked by a user, displays a message indicating that the value is being saved to avoid duplicates. However, when attempting to handle this on the server side controller, I enco ...

Does the onchange function in the dropdown list only work when the first item is changed?

Here is a snippet of my HTML code featuring a list item generated from a database using a foreach loop: <select class="form-control select" id="inventoryitem" name="inventoryitem" onchange="getunit();"> <option>---Select an item---</o ...

"Encountered an error while trying to define a Boolean variable due

I am in the process of creating a TF2 trading bot with price checking capabilities. I encounter an issue while trying to define a boolean variable to determine if the item is priced in keys or not. My attempt at replacing isKeys with data[baseName].prices ...

Incorporating an NPM module into a React file: Webpack encounters resolution issues

After reviewing information from this source and here, the process of publishing a react module to NPM and then using it in another project while having the component in the node_modules directory should be as follows: Create and export a module Specify ...

Update the color of the text depending on the background color

When hovering over my CTA, a sliding effect occurs. However, I am facing an issue with the text being difficult to read depending on the background color. To better understand what I'm trying to achieve, you can view the demo here: Demo on CodePen T ...

Retrieve all items from the firebase database

I have a query. Can we fetch all items from a particular node using a Firebase cloud function with an HTTP Trigger? Essentially, calling this function would retrieve all objects, similar to a "GET All" operation. My next question is: I am aware of the onW ...

@mui/x-date-pickers styling for the DatePicker component

Despite numerous attempts, I have been unsuccessful in styling the @mui/x-date-pickers <DatePicker/> component. I've experimented with various methods such as sx={{}}, style={{}}, makeStyles(), .css with the !important rule, renderInput={(param ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

Error: Unable to decode productsTest.json file from application bundle

A notification popped up showing "Build Succeeded". However, on the canvas, an error message displayed saying "Could not view this file - crashed". Subsequently, the application crashed. The issue seems to originate from JSONDecoder.sw ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Executing an AngularJS function through CasperJS is a common task that can

I am facing a challenge with testing a directive within a controller. The unit tests I am trying to write involve executing this code, which is triggered not by a click event but rather by a socket.io emit. Instead of attempting to mock socket.io, I am exp ...

Enhance your browsing experience with a JavaScript bookmarklet that allows you to easily search through

Struggling to develop a JS Bookmarklet that scans the source code of the current page for a specific code like "G1_Value_client." If found, I need it to trigger alert A; if not found, trigger alert B. Seeking assistance as I am facing some challenges with ...

Obtaining an address using latitudes and longitudes with React Google Maps

I created a map using the react-google-map plugin where users can drag the marker to get the latitude and longitude of a location. However, I am only able to retrieve the lat and lng values and not the address. How can I obtain the address as well? Take a ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...