5

I have the below JSON object array which I get back from the server. However while the server sends back the response the data is enclosed in "" and that then makes the javascript function thing this is a String and not an Array.

"[  
    [32.361346650846805,50.90932315437885],
    [32.36743646734031,50.95189517586323],
    [32.35467638118774,50.95876163094135],
    [32.342494619322636,50.904516635824166],
    [32.36279664436138,50.90039676277729],
    [32.380194752587755,50.899023471761666],
    [32.3648265962154,50.91481631844135],
    [32.361346650846805,50.90932315437885]
]"

I just need to get the String into an array and use a for loop to iterate in the set of elements in the array. However since it is being treated a string it is not possible to iterate using a for loop.

any help?

4
  • 3
    JSON.parse can be your friend... Commented Aug 1, 2018 at 16:55
  • How are you getting this JSON from server? Via ajax? Commented Aug 1, 2018 at 16:55
  • 1
    var result = JSON.parse(str) Commented Aug 1, 2018 at 16:56
  • 1
    That is not JSON, it is a multidimensional array. Commented Aug 1, 2018 at 17:02

1 Answer 1

10

You just need to run this through JSON.parse(), which is supported by almost all the JavaScript parsers:

console.log(JSON.parse(`[  
    [32.361346650846805,50.90932315437885],
    [32.36743646734031,50.95189517586323],
    [32.35467638118774,50.95876163094135],
    [32.342494619322636,50.904516635824166],
    [32.36279664436138,50.90039676277729],
    [32.380194752587755,50.899023471761666],
    [32.3648265962154,50.91481631844135],
    [32.361346650846805,50.90932315437885]
]`));

Just beware that the JavaScript might not like having line-breaks in strings if you give them in source code. If the original string does have line-breaks, that's totally fine. That's why I have used a template literal here.

// Say you have your string here.
var str = `[  
    [32.361346650846805,50.90932315437885],
    [32.36743646734031,50.95189517586323],
    [32.35467638118774,50.95876163094135],
    [32.342494619322636,50.904516635824166],
    [32.36279664436138,50.90039676277729],
    [32.380194752587755,50.899023471761666],
    [32.3648265962154,50.91481631844135],
    [32.361346650846805,50.90932315437885]
]`;
// Convert to array.
var arr = JSON.parse(str);
// Loop throught the array.
for (var i = 0; i < arr.length; i++)
  console.log(arr[i]);

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

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.