user

Jo Micheal

30 Jan 2022

[solved] SyntaxError: Unexpected token o in JSON at position 1 jQuery

jQuery

I am trying to use JSON.parse() to convert the text of JSON to objects but when I run the code I get this error 
SyntaxError: Unexpected token o in JSON at position 1
The JSON example which I am using is 

jQuery(document).ready(($) => {
 //Create variable to store the JSON 
 var data = [
 { 
 "id": 3,
 "title": "Lets narrow down your selection",
 "subtitle": "What services do you want to include in your selection?",
 "answers":[
 { "name": "Driver Profiling", "value": "0" },
 { "name": "Driver Assessment", "value": "1" },
 { "name": "Driver Training", "value": "2" },
 { "name": "Driver Management", "value": "3" },
 { "name": "Driver License check", "value": "4" },
 ]
 },
 ];
 let test = JSON.parse(data);
 console.log(test);
});

What should I do?

Comments

Mohamed Atef

30 Jan 2022

Best Answer

best answer
githubgithubgithub

HII,
This must be a JSON typing error because the JS code is totally correct,
I noticed that you not using ‘ or " to store the JSON into the variable and that’s a mistake you should use it like 

jQuery(document).ready(($) => {
 //Create variable to store the JSON 
 var data = `[
 { 
 "id": 3,
 "title": "Lets narrow down your selection",
 "subtitle": "What services do you want to include in your selection?",
 "answers":[
 { "name": "Driver Profiling", "value": "0" },
 { "name": "Driver Assessment", "value": "1" },
 { "name": "Driver Training", "value": "2" },
 { "name": "Driver Management", "value": "3" },
 { "name": "Driver License check", "value": "4" }
 ]
 },
 ]`;
 let test = JSON.parse(data);
 console.log(test);
});
  1. as you see I added ` at the beginning & the end of the JSON array so be like regular text then you can pass it into the function
  2. There are comma “ , ” at the end of the last object into the Array of answers and this is a mistake  

 

Replies

Jo Micheal

30 Jan 2022

Yea that's it the JSON code you attached is working so good, sorry this is a beginners mistakes :)

© 2024 Copyrights reserved for web-brackets.com