简体   繁体   中英

How to decode JSON-like JavaScript Object Literal Strings

I'm having trouble decoding an array of strings from what I thought was JSON.

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'}"
];

You can see that there are 3 gene-related strings of JavaScript object literals, each encoded as a string. How can I decode these?

I tried JSON.parse but it gives me an error.

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

Uncaught SyntaxError: Unexpected token g .

Is there a simple way?

What you have is not JSON, but Javascript objects in text form. You can convert them to Javascript objects with eval() :

  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); } 

Note: eval is generally held to be evil. In this case it's safe enough if you're absolutely sure that the source array will only ever hold data, and no code.

Since this is valid javascript, you can use Function() to return a new instance of the object by creating an anonymous function and then immediately executing it. Unlike the other answer with eval() , you don't have to declare a variable and assign the object literal to that variable in the string passed to eval - everything you need can be done cleanly in one line.

 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'}" ]; for (var i = 0; i < result.length; i++) { // create function that returns the obj literal // and call it immedieately. var obj = new Function( 'return ' + result[i] + ';' )(); document.write('gene: ' + obj.gene + ' <br />'); } 

The JSON format requires double quotes around property names. Your sample data lacks these quotes, and this is not valid JSON.

It also requires double quoted values, not single quoted.

Try something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM