Hello good I have a problem I have this array that throws me as a string
[{TCAD: "[{name:'RURAL',y:0.186838},{name:'URBANA',y:0.805798}]"}]
I got the TCAD value with the method:
this.jsonmap[0].TCAD;
As a result it throws me the value inside TCAD
[{name:'RURAL',y:0.186838},{name:'URBANA',y:0.805798}]
I would like to convert that string to an Array
[
{
"name":"RURAL",
"y":0.186838
},
{
"name":"URBANA",
"y":0.805798
}
]
You have several options. The first option, easy and direct since you are using
angular
, is to install the JSON5 library that allows you to do it:The second option, and somewhat more complex, is to parse it yourself. You can check this post as a reference for it and I attached a possible example that works with your format. The idea is to modify the string to fit it into a format
json
that it can decodeJSON.parse()
. The advantage is obvious, it does not require external libraries.For your particular case, you only need to add quotes to the braces and replace the single quote with the double:
The last, but the most dangerous for security reasons is to use
eval
. Check the MDN recommendations before using it, although insecurity really depends on the source from which you get thestring
. Consider the options above before using this one: