简体   繁体   中英

SyntaxError: JSON Parse error: Unexpected identifier “object” when trying to parse json

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

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

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)

}

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