Is there a way to access a JavaScript object using Perl?

Looking to manipulate a JavaScript Object file with 5.5mb of longitude latitude data? Consider opening it in Perl for applying a detail-reducing algorithm that will generate a new object file with reduced dataset. My approach involves using a for loop to select every 20th long/lat pair.

While I can achieve this in JavaScript, it requires manual copying and pasting each coordinate set to run the script individually.

Initially, I considered storing coordinates in a SQL database but found it inefficient due to excessive data movement.

Opting for Perl seems like a more server-friendly solution. Here's a snippet showcasing how to open the file:

#!/usr/bin/perl

# Open file
open(FILE, "reduced_object_latlng.js") or die("Unable to open file");

# Read file into an array
@data = <FILE>;

# Close file 
close(FILE);

# Print file contents
foreach $line (@data)
{
    print $line;
}

The structure of the object is defined as:

var paths = {
    mayo: {
        name: 'Mayo',
        colour: 'green',
        coordinates: '-9.854892,53.76898 -9.853634,53.769338 -9.85282,53.769387 -9.851981,53.769561 -9.850952,53.769508 -9.850129,53.769371 -9.849136,53.769171 **data**' 
    },
    galway: {
        name: 'Galway',
        colour: 'purple',
        coordinates: '**data**;
    }
}; //etc.

To demonstrate the reduction process used in JavaScript, my version loads data from a file with one var coords = "*data*"

coords = coords.split(" ");
var path = [];
    var output="";
    document.getElementById("map_canvas").innerHTML = "";
for (var i = 0; i < coords.length; i++) {
        if (i%20==0)
        {
            var coord = coords[i].split(",");
            output += coord[0]+","+coord[1]+" ";
        }
}
document.getElementById("map_canvas").innerHTML = output;

Suggestions have been made to convert data to JSON format, although unsure of necessity. Wanting to avoid manual text manipulation, is there a method to load the file directly as an object?


Due to time constraints, approached the task by:

var outputobject = 'var paths = {';
    for (property in copypaths) {
        outputobject += property + ': { ';
        outputobject += "name: '" + copypaths[property].name+"',";
        outputobject += "colour: '"+ copypaths[property].colour+"',";

        var reducedoutput="";
        var coord = copypaths[property].coordinates.split(" ");
        for (var i = 0; i < coord.length; i++) {
            if (i%20==0)
            {
                var coords = coord[i].split(",");
                reducedoutput += coords[0]+","+coords[1]+" ";
            }
        }   
        outputobject += "coordinates: '"+ reducedoutput+"'},";
    }
    outputobject += "};";
    document.getElementById("reduced").innerHTML = outputobject;

This method still involves some manual intervention such as copy/pasting and removing the last ,.

Thank you @Oleg V. Volkov for your insights, I plan to explore your method further when time permits later this week.

Answer №1

To create valid JSON data with bare keys, first remove any leading JavaScript and then utilize a JSON/JSON::PP instance. Make sure to set the allow_barekey parameter to true when decoding the resulting string.

Answer №2

To handle less stringent JSON syntax, utilize JSON. This allows for flexibility in decoding different types of data by using the following options:

  • allow_singlequote: permits single-quoted and double-quoted strings

  • allow_barekey: enables hash keys to be alphanumeric without quotes

  • decode_prefix: ignores additional data after primary content

  • relaxed: just for good measure

The code below demonstrates how to decode JSON into a Perl structure, extract coordinate information for the mayo entry, and display the coordinates in pairs.

Note: In the provided JavaScript data, corrected a potential mistake at coordinates: '**data**; (assumed not actual JavaScript data)

use strict;
use warnings;

use JSON -support_by_pp;

my $json = JSON->new->relaxed->allow_singlequote->allow_barekey;

my $data = do {
  local $/;
  <DATA>;
};

my ($hash) = $json->decode_prefix($data =~ /(\{.*)/s);

my @coords = $hash->{mayo}{coordinates} =~ /[-0-9.]+/g;

printf "%f %f\n", splice @coords, 0, 2 while @coords;

__DATA__
var paths = {
    mayo: {
        name: 'Mayo',
        colour: 'green',
        coordinates: '-9.854892,53.76898 -9.853634,53.769338 -9.85282,53.769387 -9.851981,53.769561 -9.850952,53.769508 -9.850129,53.769371 -9.849136,53.769171 **data**' 
    },
    galway: {
        name: 'Galway',
        colour: 'purple',
        coordinates: '**data**'
    }
}; //etc.

output

-9.854892 53.768980
-9.853634 53.769338
-9.852820 53.769387
-9.851981 53.769561
-9.850952 53.769508
-9.850129 53.769371
-9.849136 53.769171

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

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Learn how to successfully upload an image using React and Node without having to rely on

I am currently exploring file uploading in react/node. Instead of passing files directly into the API request, I am passing them within the body of the request. Here is a snippet of my react code: import React, { Component } from 'react'; import ...

Subdomain redirection issue with express-subdomain for localhost GET requests

In order to manage requests to specific subdomains, I am utilizing a package in express.js called express-subdomain. From my understanding, the subdomain constructor function requires an express router object that I pass from an exported router module. M ...

Trouble in sending email with attachment using Microsoft Graph

I have been working on an application that has the functionality to send emails from a User, following the guidelines provided in this article. Despite everything else functioning correctly, I'm facing an issue when trying to include attachments. The ...

How can ReactJS continuously dispatch promises after a set interval?

Within my React component, I am invoking an action in ComponentDidMount() as shown below: componentDidMount() { const { actions } = this.props function save_project_continuously() { console.log("inside") actions.sa ...

Steps for successfully sending data to a MenuItem event handlerExplanation on how to

My issue arises when I attempt to render a Menu for each element in an array, as the click handlers for the items only receive the final element in the array rather than the specific element used for that particular render. The scenario involves having a ...

"Unraveling the Mysteries of Basic WebGL Sh

Trying to wrap my head around WebGL shaders, but it's like trying to untangle a mess of spaghetti. Here's what I've managed to put together: <script type="x-shader/x-vertex" id="vertexshader"> #ifdef GL_ES precision highp ...

JavaScript Simplified Data Sorting after Reduction

I have extracted data from a JSON file and successfully condensed it to show the number of occurrences. Now, my next step is to arrange these occurrences in descending order, starting with the most frequent. To illustrate: var myData = [{ "datapo ...

Utilizing Angular Components Across Various Layers: A Guide

Consider the following component structure: app1 -- app1.component.html -- app1.component.ts parent1 parent2 app2 -- app2.component.html -- app2.component.ts Is it possible to efficiently reuse the app2 component within the ap ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

When hovering over, my text and image shift to the left in a strange and abnormal manner

Recently, I made a small code addition to an existing one in order to display text below an image and have the text highlighted in blue on mouse over. Everything seemed to be working fine until I noticed that on mouseover, the text and image shifted to the ...

Issues with JQuery `.click()` event

Check out this snippet of code I'm working with: $(".item").click(function () { alert("clicked!"); }); I also have (hypothetically; in reality it's more complex) the following HTML on my page: <a href="#" class="item"> ...

Issue with replacing fragment shader in three.js not resolved in versions above 131

I have created an example showcasing the replacement of standard material (fragment and vertex shader) that was functioning properly in three.js versions prior to r131. However, in releases above 131, the changes made to the fragment shader are no longer w ...

Steps to create a hover effect similar to that of a website (increasing grid size on hover)

Looking to create a hover effect for my boxes similar to the one on this website: I've examined the code of the website above and searched extensively for a similar feature without any luck. Could anyone offer assistance with this, please? ...

Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal ...

How can I use AJAX to read an image file and display it on a Canvas?

Is there a way to read an image from my server using Ajax and then display it on Canvas? I am aware that this can be achieved by using normal image tags and canvas draw methods, as shown below: <img id="myImage" src="./ColorTable.PNG" style="display:n ...

Finding the main directory in JavaScript: a step-by-step guide

My website uses mod_rewrite to reformat the URLs like this: The issue arises when making AJAX calls to a file: I want to access login.php from the root without specifying the full URL or using the "../" method due to varying folder levels. So, I need a ...

An unexpected error occurred: ReferenceError - document is undefined

Error Alert: Unhandled Runtime Error ReferenceError: doc is not defined Source of Issue components\Modal.js (42:18) @ updateDoc 40 | await uploadString(imageRef, selectedFile, "data_url").then(async (snapshot) => { 41 | const do ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

What are some ways to utilize an empty array that has been declared in React's initial state?

I am currently in the process of developing an application that displays a collection of various lists. However, I have encountered a roadblock when attempting to access an empty array that I initialized when setting up the initial state. Here is the state ...