Tonybho Tonybho - 1 year ago 106
JSON Question

Morris Chart convert data from string to object

I have this string variable built dynamically:

var vData = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";

How can I convert my string variable into an array to pass the data parameter?

I've tryed in Javascript with:
, but don't work.
In a separated PHP file, I've tryed with:
echo json_encode($arr);
at the end of PHP file, but don't work.

Where am I wrong?

Answer Source

You'll have to wrap your strings and property names in double quotes for JSON.parse to work. E.g.: [{"value": 7, "label": "1"}]

I'd strongly suggest fixing this in your string generation code, but just to show you it works (definitely not the right regex approach):

var data = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";

data = data.replace(/value/g, '"value"');
data = data.replace(/label/g, '"label"');
data = data.replace(/\'/g, '"'); 


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download