简体   繁体   中英

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: JSON.parse(vData) , 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?

You'll have to wrap your strings and property names in double quotes for JSON.parse to work. Eg: [{"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, '"'); console.log(JSON.parse(data)); 

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