1

I'm getting errors when trying to parse a string to json

here is my String

{"location": " Antoine Vallasois Ave, Vacoas-Phoenix, England", "stopover":true}

and here is my javascript function

function fillWaypoints(location){
 var ob =JSON.parse(location);
 ArrayWaypoints.push(ob)
 
}
Nicky Larson
  • 43
  • 2
  • 7

2 Answers2

0

There are some issues here:

  1. location is a keyword in JavaScript, you cannot pass that as parameter to a function.

  2. location value " Antoine Vallasois Ave, Vacoas-Phoenix, England", "stopover":true is not a valid JSON, so it will give you an error.

  3. You didn't declare ArrayWaypoints.

You can try the following way:

var loc = {"location": " Antoine Vallasois Ave, Vacoas-Phoenix, England", "stopover":true}
var ArrayWaypoints = [];
function fillWaypoints(loc){
  loc.location.split(',').forEach(function(l){
    ArrayWaypoints.push(l.trim());
  });
}
fillWaypoints(loc);
console.log(ArrayWaypoints);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • TypeError: null is not an object (evaluating 'ArrayWaypoints.push') – Nicky Larson Mar 13 '18 at 04:09
  • @NickyLarson, what is not working? what is the output you are expecting? Did you run the snippet of my answer? – Mamun Mar 13 '18 at 04:11
  • with my codes i'm getting TypeError: null is not an object (evaluating 'ArrayWaypoints.push') – Nicky Larson Mar 13 '18 at 04:14
  • sorry it looks like I messed up something with array var ArrayWaypoints = [] , xD I've defined it as **var ArrayWaypoints = JSON.parse(sessionStorage.getItem('myArray'));** – Nicky Larson Mar 13 '18 at 04:19
  • @NickyLarson, you are most welcome. Great to know that you are able to get going.......thanks. – Mamun Mar 13 '18 at 04:21
0

Hey Please Note Here You are trying to parse Json.. You have to pass string in JSON.parse() function because JSON.parse can only parse string into json:-

var a = '{"location": " Antoine Vallasois Ave Vacoas-Phoenix England", "stopover":true}'

let ArrayWaypoints = [];

function fillWaypoints(location){
    var ob =JSON.parse(location);
    ArrayWaypoints.push(ob)

}
Bhavin Padiya
  • 87
  • 2
  • 14