2

I've a string

var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";

I need to convert it into an array of list. For example,

alert(my_str[1])

would give an output of 1,15.

I've tried the following:

var myarray = JSON.parse(my_str);

but it throws the error "unexpected token ( in JSON at position 1"

2
  • var myarray = JSON.parse(my_str); but it throws error "unexpected token ( in JSON at position 1" Commented Aug 27, 2016 at 22:22
  • Add your comment section part also in to the question. Then it would be more clear. Commented Aug 28, 2016 at 7:18

5 Answers 5

2

I tried this

var myarray = JSON.parse(my_str); 

but it throws error "unexpected token ( in JSON at position 1"

So I changed the structure of my string to:

var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";

That worked like a charm ;)

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

Comments

1

The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")". Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.

var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))

you can now work on my_array object and retrieve couples of numbers using array indexes

my_array[1] ---> 1,15

1 Comment

Yes you're rite, my syntax is not right. I corrected that n simply used Json.parse(my_str); thanks
0

You have to replace ( by '( and ) by )' ,, then , apply eval :

eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]

Comments

0

This is a pretty naive idea, but does work (without JSON.parse or eval):

var arr = my_str.replace('[(', '').replace(')]', '').split('),(');

//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]

Comments

0
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

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.