I am working on a quiz app for class and I keep getting the error "Uncaught SyntaxError: Unexpected token o in JSON at position 1" in the console. I have tried looking up YouTube videos for solutions and have even tried fixing the code through similar posts on this site. I am at a loss and can't figure out what is wrong.
const username = document.querySelector('#username');
const saveScoreBtn = document.querySelector('#saveScoreBtn');
const finalScore = document.querySelector('#finalScore');
const mostRecentScore = localStorage.getItem('mostRecentScore');
const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
const MAX_HIGH_SCORES = 5;
finalScore.innerText = mostRecentScore;
username.addEventListener('keyup', () => {
saveScoreBtn.disabled = !username.value;
});
saveHighScore = e => {
e.preventDefault();
const score = {
score: mostRecentScore,
name: username.value
};
highScores.push(score);
highScores.sort((a,b) =>{
return b.score - a.score;
})
highScores.splice(5);
localStorage.setItem('highscores', JSON.stringify(highScores));
window.location.assign('../high-scores/highscores.html')
};
"Uncaught SyntaxError: Unexpected token o in JSON at position 1"
That means this is not json formated code. Check your json again.
Related
function json_data () {
const url = "https://in.investing.com/economic-calendar/historical-data-table?eventId=201"
const res = UrlFetchApp.fetch(url,{muteHttpExceptions: true});
const data = JSON.parse(JSON.parse(res.getContentText));
const result = data.map(post => {
return [post["release_date"],post["actual"]]
})
return result
}
this is my first time writing in a programming language, I am running this program code in Google-Sheet App-Script. the result I am receiving either comes as null or undefined, I am not even sure if it is the proper JSON file I am requesting. a segment of source URL I am trying to request:
{"release_date":"Oct 24, 2022 (Oct)","time":"13:30","actual":"46.6","forecast":"47.8","previous":"48.4","metaData":{"timestamp":1666598400,"perliminary":true,"color":{"actual":"u-down","previous":""}
change this line :
const data = JSON.parse(JSON.parse(res.getContentText));
to
const data = JSON.parse(JSON.stringify(res.getContentText()));
( also you can remove extra JSON.parse(JSON.stringify()) entirely )
I am making a messaging system using firebase. It properly sends messages to firebase, however when I send messages, it keeps throwing the error:
Uncaught TypeError: sendToServer(...) is not a function
at sendToP.js:21
at EventRegistration.ts:109
at Qe (util.ts:539)
at EventQueue.ts:159
at Pi (EventQueue.ts:127)
at Ii (EventQueue.ts:107)
at wo (Repo.ts:365)
at ro.s.server_ [as onDataUpdate_] (Repo.ts:230)
at ro.onDataPush_ (PersistentConnection.ts:661)
at ro.onDataMessage_ (PersistentConnection.ts:654)
Here is the function that adds the message to the database
function cleanMessage(message){
message = message.split(" ").map(x => badWords.indexOf(x) != -1? x = (x.split("").map(c => c = '*')).join(""): x = x).join(" ")
return message
}
function sendToServer(obj) {
autoId = firebase.database().ref('users').push().key
firebase.database().ref('/general/' + autoId.toString()).set(obj)
}
$(".send").click(function() {
firebase.database().ref('Users/' + firebase.auth().currentUser.uid).on('value', function(snapshot) {
digits = snapshot.val().digits
let message = cleanMessage($(".enter-message").val())
let messageObject = {
message: message,
sender: digits
}
sendToServer(messageObject)
$(".enter-message").val('')
});
})
Here is the function that gets the last message. Note: This is on a separate script
// Add message to the browser window
firebase.database().ref('general').orderByKey().limitToLast(1).on("value", function(snapshot){
message = ""
snapshot.forEach(function(elem){
message = elem.val().message
})
})
I greatly appreciate any help.
Im really stuck on this figuring out what did I miss, Im not that expert about javascript, if someone can please tell me what I did wrong, I really appreciate.
I have a working code:
if (value_ == "group") {
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
var data = JSON.parse(data);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
});
}
the code above will work and get every data I wanted, but the json is from the:
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
then I tried to get the json from the URL which return the same value as the var data above. But it doesn' work.
which I did change var data = JSON.parse(data); into data = JSON.parse(json)
and delete "var data = { "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] };"
And it does give an error: (node:10868) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input
I also tried this code:
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
parseJSON(JSON.stringify(json));
function parseJSON(str){
var data = JSON.parse(str);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
}
});
}
this give me error: (node:12668) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined.
Thanks and pardon my english.
You don't need to execute JSON.parse manually because the content of json variable in the third line of your example is already an object.
Try this:
fetch("http://localhost/someapi"+value_)
.then(r => r.json())
.then(json => {
var groupName = json.group.map(current => current.name);
var groupTag = json.group.map(current => current.tag);
console.log('groupName', groupName);
console.log('groupTag', groupTag);
});
I am getting this error in console when i click submit button though my data is getting saved to backend as i wanted.
SyntaxError: Unexpected token T in JSON at position 0
at JSON.parse (<anonymous>)
at dc (angular.min.js:91)
at angular.min.js:92
at q (angular.min.js:7)
at gd (angular.min.js:92)
at f (angular.min.js:94)
at angular.min.js:131
at m.$digest (angular.min.js:142)
at m.$apply (angular.min.js:146)
at l (angular.min.js:97)
Here is my frontend code in angular
$scope.nextStep = function() {
if ($scope.selection === 'Information'){
$scope.branch.organisation = $scope.branch.organisation.id;
$scope.fact.incrementStep($scope);
}
else if ($scope.selection === 'Validation'){
var authdata = base64.encode($rootScope.globals.currentUser.user.phone + ':' + $scope.password.password);
if (authdata === $rootScope.globals.currentUser.authdata){
$scope.passwordMatch = true;
var branchArr = [];
var dynamicBranches = $scope.dynamicBranches;
for (var i = 0; i < dynamicBranches.length; i++) {
branchArr.push(dynamicBranches[i].name);
}
var params = [{
"region" : $scope.branch.region,
"branches" : branchArr
}];
Restangular.one('organisation', $scope.branch.organisation).all('add_region_and_branch_data').post(params).then(function(response) {
$scope.createdBranch = response;
$scope.fact.incrementStep($scope);
}, function(error){
///console.log('Error with status', error.statusText, 'code', error.status);
//SweetAlert.swal('Error', 'The agent couldn\'t be created. \n' + error.data.error, 'error');
console.log(error);
});
}else{
$scope.passwordMatch = false;
}
}
};
Again, my data is getting saved to api but I am getting this error. How can i fix this?
Check your HTTP-response body. AngularJS gets something what it can't parse like JSON. May be any warning or error happened and added to your API-response? I thing a problem is not in your nextStep function.
Unexpected token T in JSON at position 0 problem can happen, for example, with this HTTP-responses:
Too many params warning{"here": "is valid JSON"}
Or just warning
Too many params warning
I'm trying to count the number of misbehavior on the two routes I've made in my database. Below are the structure of my firebase database under drivers and reports database respectively:
[drivers database] - i.stack.imgur.com/Q6GKs.png
[reports database] - i.stack.imgur.com/ALWPu.png
Here's my counter for counting the number of misbehavior:
<script>
var route1Count = 0;
var route2Count = 0;
var drivers;
var reports;
var driversRef = firebase.database().ref('drivers/');
var reportsRef = firebase.database().ref('reports/');
driversRef.once('value', (snapshot) => {
drivers = snapshot;
});
reportsRef.once('value', (snapshot) => {
reports = snapshot;
});
drivers.forEach((driver) => {
var violationCount = reports.filter((report) => report.val().plateNumber === driver.key).length;
if(driver.val().route === "Fairview - Quiapo"){
route1Count += violationCount;
}else if(driver.val().route === "Quiapo - Fairview"){
route2Count += violationCount;
}
});
document.getElementById("demo").innerHTML = "route1: " + route1Count + "route2: " + route2Count;
</script>
I get this error message:
Uncaught TypeError: Cannot read property 'forEach' of undefined
at drivers.forEach, all inputs will be greatly appreciated! Thanks!
Error Message :
you could nest them, or if you run this in an environment that supports es6's Promise object (which your code suggests), you could use the once() returning a promise and more elegantly do:
Promise.all([driversRef.once('value'), reportsRef.once('value')])
.then(([driversSnapshot, reportsSnapshot]) => {
// ...
})