Unraveling JavaScript Object Literal Strings that resemble JSON

I'm encountering difficulty with decoding an array of strings that I initially thought were in JSON format.

var result = [
  "{gene: 'PEX2', go_bp: '0.766500871709', CombinedPvalue: '9.999999995E-4'}",
  "{gene: 'PEX5', go_bp: '0.766472586087', CombinedPvalue: '9.999999995E-4'}",
  "{gene: 'PEX7', go_bp: '0.766386859737', CombinedPvalue: '9.999999995E-4'}"
];

These are three instances of gene-related strings represented as JavaScript object literals, contained within a string. How can these be decoded?

My attempt to use JSON.parse resulted in an error:

for (var i = 0; i < result.length; i++) 
    console.log(JSON.parse(result[i]));

The error message received was:

Uncaught SyntaxError: Unexpected token g
.

Is there a more straightforward solution for this issue?

Answer №1

One way to utilize valid javascript is to employ the Function() method in order to generate a fresh instance of the object through the creation and immediate execution of an anonymous function. This approach differs from using eval() as it eliminates the need to declare a variable and assign the object literal within the string supplied to eval - streamlining the process into a single line.

var data = [
    "{name: 'apple', color: 'red', price: '$1'}",
    "{name: 'banana', color: 'yellow', price: '$0.50'}",
    "{name: 'orange', color: 'orange', price: '$1.25'}"
];

for (var i = 0; i < data.length; i++) {
    // create function to return obj literal
    // and execute immediately.
    var newObj = new Function( 'return ' + data[i] + ';' )();
    document.write('Name: ' + newObj.name + ' <br />');
}

Answer №2

If you have some data that looks like JavaScript objects in text format instead of JSON, you can easily convert them into JavaScript objects using the eval() function:

    var result = [
      "{gene: 'PEX2', go_bp: '0.766500871709', CombinedPvalue: '9.999999995E-4'}",
      "{gene: 'PEX5', go_bp: '0.766472586087', CombinedPvalue: '9.999999995E-4'}",
      "{gene: 'PEX7', go_bp: '0.766386859737', CombinedPvalue: '9.999999995E-4'}"
    ];

    var f;
    for (var i = 0; i < result.length; i++) {
        eval("f = "+result[i]);
        console.log(f.gene);
    }

Please note that while eval is generally considered risky, it should be safe to use in this specific case as long as you are confident that the source array contains only data and no malicious code.

Answer №3

Remember, when using JSON format, make sure to always include double quotes around property names. Your current data does not follow this rule, making it invalid JSON.

Additionally, be sure to use double quotes for values instead of single quotes.

Here's an example of properly formatted JSON:

   '{"gene": "PEX2", "go_bp": "0.766500871709", "CombinedPvalue": "9.999999995E-4"}',

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

Insert the variable into the specified div ID

I am looking to implement an incremental div id system to ensure all my ids are unique. This way, I can make use of jQuery effects to customize them individually. Let me know if you need further clarification on my query. div id ="name_$id" Perhaps I sh ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

Passing error messages from a grandchild component to a grandparent component in React

Is there a way to pass a message from a fetch call in a grand-child component to a grand-parent component? While the concept of lifting state, as explained in the React documentation, is commonly used for scenarios where a user interacts with a button, ot ...

The fetch API in Javascript encounters issues when employed within an EJS file

I'm attempting to retrieve a file named files.json from the main directory of my locally hosted NodeJS backend and then display its contents in the console. <script> fetch("./files.json") .then(res => { return res.json() ...

Having trouble getting getStaticProps to display JSX in Next.JS

I'm currently facing an issue with rendering basic data from a locally hosted Strapi API in my Next.js project. Although the data is successfully logged in the console, I am unable to map it into JSX. Below is the API get function: export async func ...

Utilizing the OrientDB HTTP API within an Angular platform - a comprehensive guide

When trying to query OrientDB from an Angular service method, authentication-related errors are encountered. It appears that two GET requests are required for successful querying of OrientDB. An Authentication call: Requesting http://localhost:2480/conne ...

Exploring JSON encoding specifics

While exploring the concise language specification of JSON, I came across a surprising sentence: Aside from a few encoding nuances, that statement fully encapsulates the language. What specific details have the potential to challenge those straightforwar ...

Error in Flask app: Stripe Elements - "400 bad request: CSRF token not found or invalid"

Currently, I am in the process of following the Stripe Quickstart guide for integrating stripe Elements with Flask. While working through the tutorial available at https://stripe.com/docs/stripe-js/elements/quickstart, I encountered an issue - the token ap ...

Navigate to specific routes only when a user is signed in using the Route render feature in React Router

I'm having trouble figuring out how to display the signIn component when currentUser is not detected. There are no errors, but it's rendering an empty component because of the value "currentUser = null". <Routes> <Route exact path=&ap ...

Obtain a button located within a div using a JavaScript file

I am currently immersed in a MVC ASP .NET Project. Within my View folder resides the Dashoboard.cshtml file, which contains the following code: <div id="something"> <button type="button" class="btn btn-primary">Export To PDF</b ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Strategies for refining outputs from Controller within the View

I am facing a challenge where I need to display certain elements in my View and then filter them based on user selection. I attempted to compare variables from the controller result with a JavaScript variable, but unfortunately, it seems that this approach ...

Tips for modifying the hue of the hint attribute within vue.js?

`<v-text-field id="loginPasswordId" ref="password" v-model="password" class="login-input" dense :disabled="loading" :hint="hello world" :loading="loading" maxlength= ...

Storing information in a JSON file using PHP

My attempt to update a JSON file: First approach: $filename = "$root/nachrichten/bla.json"; $neueartikel = json_decode(file_get_contents($filename), true); /*this part works as expected, I can iterate through the file*/ $neueartikel[] = array('tit ...

transforming a CSV document into a JSON format

I am currently working on converting a CSV file into a JSON file based on a specific column value. Here is an example of how the CSV file is structured: ID Name Age CSE001 John 18 CSE002 Marie 20 ECE001 ...

Tips for creating an output directory when the TypeScript files are stored in the './src' location

Here is what I currently have: ./src/myfile.ts ./test/mytest.spec.ts I want tsc to output a javascript file (myfile.js) and a definition file (myfile.d.ts) in the ./build directory. This is my tsconfig.ts: { "compilerOptions": { "module": "common ...

Wondering how to initiate an AJAX API function within a Windows application?

Recently, a company has provided me with a web-based API to access their services. Utilizing this API within a web browser hasn't posed any issues for me: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascri ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

Injecting CSS styles into the head tag dynamically with jQuery from within the body of a

When it comes to adding CSS to the head of an HTML page from the body using JavaScript and jQuery, I have come across two methods. One involves using jQuery to directly append the CSS to the head, while the other method involves creating a style element an ...

Creating a delayed queue using RxJS Observables can provide a powerful and

Imagine we have a line of true or false statements (we're not using a complicated data structure because we only want to store the order). Statements can be added to the line at any time and pace. An observer will remove items from this line and make ...