Convert Objecto String to Javascript Object

1

This is the string I get from an api, it is a string but not in json format, but in javascript object format, JSON.parse does not work because the key does not have double quotes "".

"{text: 1}" //string

Now I want to convert it to a javascript object that results in

{text:1} //object
    
asked by Darlyncinho Bravo 06.08.2018 в 01:43
source

2 answers

0

You could do this:

var var1 = "{text: 1}";
var aux = var1.split(':');
aux[0] = aux[0].replace('{', '');
aux[1] = aux[1].replace('}', '');
aux[1] = aux[1].replace(' ', '');
var parsed = {[aux[0]] : aux[1]};
console.log(parsed);

The output is:

    
answered by 06.08.2018 / 02:02
source
0

I am going to give you a provisional and little recommended solution but for that purpose it is useful

 var str="{text: 1}";

 eval("var j="+str);

 console.log(j);

Eval executes strings like javascript, although the use of eval is not highly recommended so you should look for another solution, if I think of a quick way (without having to process the entire string by hand) I'll put it on.

    
answered by 06.08.2018 в 02:25