简体   繁体   中英

How to parse a string from servlet to javascript and created a formatted object which contains array values

I have managed to create below string and pass it to jsp

"Dataset1:[ 10,22,33,44,55,66,7 ],Dataset2:[ 20,12,43,24,55,26,47 ],Dataset3:[ 30,12,53,64,5,16,77 ],Dataset4:[4 0,12,63,64,5,6,44 ]"

My chart function accepts data as js object described below

var graph_dataset = {
                "Dataset1":[10,22,33,44,55,66,7  ]
                ,"Dataset2":[20,12,43,24,55,26,47  ]
                ,"Dataset3":[30,12,53,64,5,16,77  ]
                ,"Dataset4":[40,12,63,64,5,6,44  ]
            };

so that I should be able to get my array (value corresponding to each key) if I call it by graph_dataset.Dataset4 .

I have tried lot of things by hit and trail including JSON.parse. Please help with a piece of code

This makes me feel dirty but it gets the job done.

 let str = "Dataset1:[ 10,22,33,44,55,66,7 ],Dataset2:[ 20,12,43,24,55,26,47 ],Dataset3:[ 30,12,53,64,5,16,77 ],Dataset4:[40,12,63,64,5,6,44 ]"; let result = str.split(',Dataset'); result[0] = result[0].split('Dataset')[1]; let obj = result.reduce( (prev, curr) => { let ar = curr.split(':'); prev['Dataset' + ar[0]] = JSON.parse(ar[1]); return prev; }, {} ); console.log(obj); 

Answering for someone who is facing similar difficulty.

I corrected the string formatting and added quotes and {} wherever applicable.

After correct formatting string looks like var str='{"Dataset1":[10,22,33,44,55,66,7],"Dataset2":[20,12,43,24,55,26,47],"Dataset3":[30,12,53,64,5,16,77]}';

I am able to parse the string and generate graph out of it successfully.

obj=JSON.parse(str);

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