0

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

1
  • it would be easier if passed a json string to the jsp, "{Dataset1:[ 10,22,33,44,55,66,7 ],Dataset2:[ 20,12,43,24,55,26,47 ] ... }" Commented Jun 16, 2017 at 21:39

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Will, for answering.. I later managed to correctly form script the string like below 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]}'; and below command is working perfectly now var graph_thread_minutes=JSON.parse(str); Thanks for your help
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.