Deciphering JavaScript String into an Object

I am currently tackling a project that involves converting a string into a JavaScript object. Despite researching various solutions and seeking answers, I have been unable to find one that addresses my specific issue.

Here's the challenge: I need to extract the content from a JS file that resembles the following structure (retrieved via a simple HTTP get request):

initiateOptions({
    fullscreen: true,
    showController: true,
    introModal: true,
    client: {
        name: 'Easyfairs - Flanders Expo',
        city: 'Gent',
        googlePlaceId: 'xxx'
    },
    preloadImages: {
        client: 'easyfairs_flandersexpo'
    },
    languages: ['EN','FR','NL'],
    logo: 'images/logo_wit.png',
    css: ['https://fonts.googleapis.com/css?family=PT+Sans', '/css/event- 
room-card.css', '/css/easyfairs.css'],
    color: '#99cc33',
    explainerImage: ['media/explainerImage.png'],
    /*customTexts: {
        switchYes: [{ "language":"NL", "text":"Beurs" },{ "language":"EN", 
"text":"Exhibition" },{ "language":"FR", "text":"Exhibition" }],
        switchNo: [{ "language":"NL", "text":"Leeg" },{ "language":"EN", 
"text":"Empty" },{ "language":"FR", "text":"Vide" }]
    },*/
});

I need to access the data within this file by converting it into a JavaScript object for proper manipulation. The content is retrieved as a string, allowing me to remove the surrounding function using string manipulation techniques.

The structure consists of a JavaScript object enclosed within a function, which also includes commented lines. Converting this format has proven to be challenging, and while eval() might solve the issue, I prefer not to rely on it.

Is there anyone out there who can provide guidance? Thank you in advance.

PS: Due to the project's established workflow, I have limited control over its structure, necessitating adaptation to the existing format.

Answer №1

There are two possible approaches to solving this issue:

  • One option is to utilize a JavaScript parser, such as Esprima. By feeding your JavaScript code into the parser and traversing the Abstract Syntax Tree (AST), you can reconstruct the object.

  • Alternatively, you can use the eval function in the following manner:

js = `initiateOptions({
    fullscreen: true,
    showController: true,
    introModal: true,
    // etc
})`


let initiateOptions = x => x;
let result = eval(js);
console.log(result)

It is not recommended to try using string functions, regular expressions, or any other method to parse it - as it may lead to inefficiencies and wasted time.

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

Using trackBy in conjunction with the async pipe

Attempting to utilize the async pipe along with *ngFor to exhibit an array of items obtained asynchronously. <ul> <li *ngFor="let item of items | async; trackBy: trackPost"> {{item.text}} </li> </ul> ngOnInit() { // a si ...

Updating the footer of a React application using Material UI Grid

Having some trouble customizing the footer in a React Material-UI grid. Refer to the image below for details. Any ideas on how to change the: 1 row selected? Thank you! ...

Implementing Autocomplete feature in Reactjs with Ant Design Library

In my React application, I created an autocomplete feature with a list of options for the user to select from. Example in Action: Click here to see the demo List of available options: const options = [ { label: "hello", value: "1" ...

Trouble displaying REACT.jsx in browser

I'm currently learning React and struggling to get it running smoothly. HTML function Person(){ return ( <div class="person"> <h1>Max</h1> <p>Your Age: 28</p> </div> ); } ...

Total sum of elements in the JSON document

In R, I have imported a geojson file called routes, which consists of polylines. The nodes are nested within lists, creating a hierarchical structure. For instance: > routes$features$geometry.coordinates[100] [[1]] [,1] [,2] [1,] 73.8460 ...

Establishing the state in componentDidMount prior to any callback functions

It has been advised not to directly use setState in the componentDidMount method. Instead, it is recommended to set state in a callback function (such as for handling ajax calls). componentDidMount() { let price = 0; const query = new URLSearchParams ...

Issue with VB code behind not executing upon button click triggered by JavaScript

A scenario arises when a user is provided with a TDF text file in a report, requiring them to select two filters and fill out two fields before being able to submit. Upon clicking the "download" button without completing these requirements, a friendly erro ...

What is the best way to validate the accuracy of an HTML form response by using PHP through $.post, all while keeping the answer confidential?

Currently, I am working on a fill-in-the-blank quiz. In my PHP file named index.php, my objective is to validate the user's input against the correct answer stored in my MySQL server. One approach I considered was to simply echo the answer using < ...

Unable to sort array within a computed property in Vue.JS

Currently, I am working on enhancing my skills in Vue.js and have encountered an issue with sorting arrays in Vue.js. Despite using the sort(a-b) method for ascending order (least alphabet/value first), the array remains unchanged. Even with a function ins ...

Setting the value of an alphabet letter in C++ involves assigning a specific character to a

I have a task to create a unique sorting algorithm for elements in an array. For instance, if the first string input is "BOB", I need to calculate the sum of the positions of each letter in the alphabet (2+15+2), then divide by the number of characters in ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

Generating multi-dimensional arrays within a JSON string

Hey there, I'm currently facing a challenge trying to get this right... Using the jqBarGraph.1.1 JavaScript library to showcase some data. The data I need to display is stored in a JSON Object that I receive. However, the tricky part is that I hav ...

Is it possible for aikau MultiSelectInput to handle multiple values?

Examining the widget configuration: { id: "MyMultiSelect", name: "alfresco/forms/controls/MultiSelectInput", config: { label: "My multi-select input", name: "assoc_myGood", width: "400px", addedAndRemovedValues: ...

Deciphering JSON data using Python for interaction with the Google Maps API

Currently, I am attempting to work with JSON in Python, but it appears that there may be a misunderstanding on my end regarding the JSON concept. I have been following the example provided by Google APIs, which has been functioning correctly. However, when ...

Refreshing Rails Views by Periodically Polling the Database

We are currently developing a statusboard to monitor all our external servers. Our database contains information about OS, software versions, and other details that are subject to frequent updates. To ensure real-time visibility of these changes on the web ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Eliminate any gaps in the input strings

I discovered this content in a selenium scrap dump: ['The Quest for Ethical Artificial Intelligence: A Conversation with Timnit Gebru', 'Mindfulness Self-Care for Students of Color', 'GPA: The Geopolitical landscape of the Olympic ...

Modifying the maximum length of input fields in HTML, Javascript, and PHP is possible by adjusting the value through

Hi there, I'm facing an issue that should be easy for you guys to help me with. I recently discovered a security flaw while using the maxlength function in HTML. Users can easily modify the maxlength attribute by inspecting elements on the website, wh ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

I'm looking to enhance my clickcounter text display by incorporating images. Can someone please help me with adding pictures to show alongside the number of clicks?

I'm currently working on a click counter onclick effect for my webpage. When the button is clicked, it displays a message like: You have clicked the button - ??? - times (??? represents the number of clicks) While the onclick effect works well, I&ap ...