Converting a function into a JSON string in JavaScript

My code contains a string that looks like this:

var jsontext = 'function(prog) {return ' + path + ';}';

I need to convert this string into javascript code.

Any ideas on how to accomplish this task?

Sincerely, Thomas

Answer №1

Although this may look like JSON, it is actually Javascript represented as a text string that needs to be evaluated.

While you can use the eval(jsontext) function for this purpose, I strongly advise against it due to security risks and performance issues. It's much safer and efficient to define your function within the script itself rather than as a string!

For more information, check out here.

Answer №2

I have encountered an issue with the eval function in the code provided below, and I am in need of a workaround.

Here is the code snippet:

function buildRecursiveFilter(filterDef) {
        var filterFuncs = [];</p>

<p>// Recursively define regex filter functions for all nodes
    naw.visitNode(filterDef, function(node, path) {

        if (typeof node !== "object") {
          var selector = eval("(function(TBM) { return " + path.toUpperCase() + "; })");
            var tester = buildRegexFilter(node, selector);         
          filterFuncs.push(tester);
        }
    }, "tbm");

    if (filterFuncs.length === 0) return noFilter;

    // Apply all test functions to tbm and provide the logical AND combination
    return function(tbm) {
        return _.reduce(
            _.map(filterFuncs, function(f) { return f(tbm); }),
            function(akku, res) { return akku && res; });
    };
}

function buildRegexFilter(filterDef, fieldSelector) {
    fieldSelector = fieldSelector || (function(tbm) { return tbm.WP; });
    var def = filterDef;
    if (typeof (def) === 'string') {
        def = def.split(',');
    }
    var filters = [].concat(def); // Force array format
    filters = _.map(filters, function(s) { return $.trim(s); });
    var expression = '(' + filters.join('|') + ')';
    var rx = expression !== '(.*)' ? new RegExp(expression) : undefined;

    return function (tbm) {
        return rx.test(fieldSelector(tbm));
    };
}

Sincerely, Thomas

Answer №3

After exploring different options, I was able to resolve the issue at hand. The problematic line containing eval has been eliminated and substituted with the following code snippet:

var method = "function(param) { return " + key.toUpperCase() + "; }";
var query = new Function("return (" + method + ")")();

Sincerely, Alice

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

Managing numerous requests from clients to a PHP page connected to a MySQL database

On my Ubuntu server, I have a mobile app that sends JSON requests to a PHP page which connects to a MySQL database. However, I've noticed that sometimes when there are a lot of requests coming in at the same time, some requests get dropped. I'm l ...

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

Combining multiple HTML elements onto a single page with just one function

I am trying to dynamically import specific HTML content into a new page, rather than the entire page itself. The issue I am encountering is that I have to create a document load function for each individual item I want to import. Is there a more efficient ...

Implementing specific actions based on user selections in an Oracle APEX navigation bar

Within the application's navigation bar, there is a Home item that is present on all pages. I want to implement a feature where if the user clicks on the Home item, a warning message will pop up based on the page number, alerting them that any unsaved ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

Understanding JSON dictionaries within Swift - "Anticipated decoding of a String resulted in discovering a dictionary instead"

Just starting out with Swift and programming, I'm facing a challenge decoding a JSON file. The JSON data I have looks like this: { "actors": { "2048": "Gary Busey", "3": "Harrison Ford ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Django Implementation of JavaScript Confirmation Dialogue

Currently working on a Django form that requires a confirm/cancel dialog upon submission. I've considered sending POST data from jQuery, but I'm curious if it's possible to integrate a JavaScript dialog as middleware instead? ...

Implementing an autosuggest feature for the TagsInput component

When developing my website, I utilized JavaScript, the React framework, and a library called mui. One of the user input features on my site is powered by TagsInput, allowing users to input data, press enter, view the tag, and optionally delete it. Unlike ...

Dynatree fails to consider the select feature while utilizing ajax requests

Currently, I am utilizing the dynatree plugin to exhibit a checkbox tree in multi-select mode (mode 3). Upon initializing the tree using ajax (without lazy loading), it appears that certain nodes that were initially loaded as selected are forgotten. When ...

What about converting the file from .rrd to JSON format?

Currently, I am undertaking a task that involves converting a .rrd database into JSON format in order to create graphs using jQuery plot. Despite attempting to follow the code provided in the documentation, I have encountered an error message stating: "s ...

I am having trouble getting any output when trying to implement this

extracting json information using jQuery $("#btn-id").click(function() { $.getJson(g, function(jd) { $("#data-id").html(jd.id + "--" + jd.email); }); }); ...

AngularJS display function is not functional

I am dealing with an HTML button <button id="postChanges" ng-show="changes.available" data-ng-click="postChanges()">Save</button> and a controller specifically for this view myApp.controller('myController', ['$scope', fu ...

The rendering of the Angular 2 D3 tree is not functioning properly

Attempting to transition a tree created with d3 (v3) in vanilla JavaScript into an Angular2 component has been challenging for me. The issue lies in displaying it correctly within the component. Below is the code snippet from tree.component.ts: import { ...

How can I display a pattern using Javascript?

Can you help me create a JavaScript program using a for loop to print a pattern with n number of asterisks and numbers like this: 1 2 3\n 4 5 6 \n 7 8 9 ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Not certain about the process of linking a JSON object to a specific web address

I'm currently working with a JSON file that contains images, and I am using a loop to display each item in a photo grid on the page. However, I am now looking for a way to assign a specific URL to each of these photos so that they point to different p ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

PHP - Encoding data to proper JSON format

I am faced with a hefty .txt file containing data structured like this: { "template_id": "prefix_1", "settings": { "setting1": "bla", "setting2": "blub" }, "test": 1, "test": 2, "test": 3 }, { "template_id": "ot ...

The text loader feature in THREE.js is failing to load

My first attempt at coding THREE.js resulted in a black screen when I tried to load the Text loader. Can someone help me resolve this issue? I kept getting the following error even after multiple attempts: three.module.js:38595 GET 404 (Not Found) ...