Converting a Perl hash into a JavaScript hash: A comprehensive guide

I am currently using the template toolkit framework and working with a Perl hash data type in my tt file. My goal is to convert this Perl hash data type into a JavaScript hash data type.

Code: template:

        [% PERL %]
        use JSON qw(encode_json);

        my $vars = {

            'version'  => 3.14,
            'days'     => [ qw( mon tue wed thu fri sat sun ) ],
            'cgi'      => CGI->new(),
            'me'       => {
                'id'     => 'abw',
                'name'   => 'Andy Wardley',
            },
        };

        my $json = encode_json($vars->{'me'});
    [% END %]


 <script>
   function callme(){
   var me = [% $json %]
  }
</script>

Now, I need to make sure that the "me" hash is accessible in JavaScript.

Answer №1

If you're looking to avoid embedding raw Perl into your template, there are numerous TT plugins at your disposal that offer better solutions. Personally, I find JSON::Escape to be my preferred choice, although there are other options available as well. After more than half a decade of working with TT on a regular basis, I have yet to rely on the [% PERL %] directive. It's worth noting that my work does not involve CGI scripting, so your mileage may vary.

[%- USE JSON.Escape( pretty => 1 );
    SET me = { id => 'abc', name => 'Alice Brown' };
...
-%]

<script>
    function callme() {
    var me = [% me.json %]
    ...
</script>

Answer №2

Consider utilizing the JSON module from CPAN. It is based on JavaScript Simple Object Notation, allowing for direct usage in JavaScript.

use JSON qw(encode_json);

my $vars = {

    'version'  => 3.14,
    'days'     => [ qw( mon tue wed thu fri sat sun ) ],
    'cgi'      => CGI->new(),
    'me'       => {
        'id'     => 'abw',
        'name'   => 'Andy Wardley',
    },
};
print encode_json($vars->{'me'});

Expected Output:

{"name":"Andy Wardley","id":"abw}

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

Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, bu ...

Troubleshooting Routing Issues in a Next.js Website Tutorial

After going through the next.js tutorial at https://github.com/zeit/next-learn-demo.git, I encountered an issue starting from stage 3 "dynamic routing". Despite the tutorial indicating that dynamic routing should be working from stages 3 to 8, it wasn&apos ...

Steps for accessing the files uploaded in a React application

Looking to implement an upload button using material UI that allows users to upload multiple files, with the goal of saving their paths into an array for future use. However, I'm unsure about where these uploaded files are stored. The code snippet be ...

Storing keys and multiple maps with React applications

Having a multiple array with an option set created, everything is functioning correctly const groups1 = OrgServices.reduce((all, cur) => ((all[cur.grouptype] ??= []).push(...cur.servicetype), all), {}); const output1 = Object.entries(groups1).map ...

The header that sticks on scroll is annoyingly blocking the content

I managed to create a sticky on-scroll header/navigation bar successfully. Here is how it looks now However, I encountered an issue. When it reaches the top, it automatically 'covers' the top part of my content, which has text on it, and I don& ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

Implementation of Gallows Game

SITUATION Recently, I took on the challenge of creating a "HANGMAN" game using JavaScript and HTML exclusively for client-side machines. The logical part of the implementation is complete, but I am facing a hurdle when it comes to enhancing the aesthetics ...

Contrary to expectations, the middleware EJS fails to render JPG files at

I am currently working on a NodeJS server using EJS. The goal of this server is to render an HTML page that contains a line of text and a jpg file. However, I am encountering an issue with the jpg file not being loaded by the server. Even though I have sp ...

Unable to activate the on('click') event when the button is loaded via AJAX

I am facing an issue with the on('click') event. I have a button that is loaded dynamically via ajax and has a click event attached to it. However, when I try clicking it, nothing happens even though the expected output should be showing an alert ...

Retrieve particular attributes from an array of objects

I have an array of JavaScript objects structured as follows: let users = [{ "id": 9, "name": "Sulaymon", "family": "Yahyaei", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deadabb2bfa7b3b1b0b6b99eb ...

AngularJS redirection to a different state by utilizing a URL

When I need to direct a user to a specific state, typically I would use the following code: $state.go('state_name'); $state.transitionTo('state_name'); This method usually takes users to /state_name. However, there is one particular s ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Attempting to single out various entities within a JSON array through the use of radio buttons

I am currently developing a website to showcase sports teams' schedules. Each team has its own JSON file containing relevant information that I aim to display upon selecting the team from a radio button. For instance, let's consider the example ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

Sending information between children components in VueORTransferring data between

So, I have a question regarding the Authentication section of my application. Within my application, I have various components and routes, including register and login. The register functionality is working properly with the API, storing both the usernam ...

Implement a transformation on the API endpoint's JSON data to prepare it for display in a React

I'm currently developing a React application and have created a component to display tabular data. The API endpoint I am calling returns data in the following format: { "bitcoin": { "usd": 48904, "usd_market_cap": 9252 ...

Implementing jQuery to add content within Redactor

I am working with a textarea field that has an ID of "description", however, it is being rendered by a WYSIWYG editor called Redactor. I am trying to use jQuery to input something in the textarea. So far, I have attempted: $('#description') ...

Is it possible to send multiple HTML input values to a Google Spreadsheet using only JavaScript?

Seeking a faster and more efficient way to send the values of multiple HTML Inputs to a specific location in a Google Spreadsheet? The existing script takes too long to complete, often skips inputs, and relies heavily on "google.script.run". Due to softwar ...

Problem with sending data using $.ajax

I stumbled upon a strange issue. In one of my php pages, I have the following simple code snippet: echo $_POST["donaldduck"]; Additionally, there is a script included which makes a $.ajax call to this php page. $.ajax({ url: "http://provawhis ...