Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript converting a string variable [closed]

Tags:

javascript

I got this:

var a = "slices: {0: {color: '#ffffff'}, 1: {color: '#fffff0'}, 2: {color: '#fff000'},3: {color: '#ff0000'}, 4: {color: '#f00000'}}";

You can see it's a string variable

I need this

draw(data, {slices: {0: {color: '#ffffff'}, 1: {color: '#fffff0'}, 2: {color: '#fff000'},3: {color: '#ff0000'}, 4: {color: '#f00000'}}, is3D: true});

As you see I need to give the variable without being a string, I tried doing

eval( "slices: {0: {color: '#ffffff'}, 1: {color: '#fffff0'}, 2: {color: '#fff000'},3: {color: '#ff0000'}, 4: {color: '#f00000'}}");

but didn't work and I cannot do this

draw(data, {a, is3D: true});

Thanks for your time.

like image 458
Jesus Avatar asked Aug 29 '26 09:08

Jesus


1 Answers

Fix your string to be valid JSON first and then:

JSON.parse('{' + a + '}');

EDIT: Antti Haapala makes a good point

JSON.parse(a);

Courtesy of crispamares:

A valid JSON is like this: "{"slices": {"0": {"color": "a"}, "1": {"color": "#fffff0"}, "2": {"color": "#fff000"},"3": {"color": "#ff0000"}, "4": {"color": "#f00000"}}}"

====

Use Crockford's JSON2 (http://www.json.org/js.html) if you need to support <IE8

like image 172
BLSully Avatar answered Sep 01 '26 00:09

BLSully