An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { before function body.

function apiurl() {
  var str = this._baseURL + '=' + (this.apikey);
  str = str.replace('=', '');
  console.log(str);
}

let a = this._getWeather(function(apiurl), function(weather) {
  if (weather) {
    this._load_forecast(weather);
  }
  // update the display with forecast
  deskletObj.displayForecast();
  deskletObj.displayCurrent();
  deskletObj.displayMeta();
});
},

I have modified the code to be:

let a = this._getWeather {
  (function(apiurl), function(weather) {
    if (weather) {
      this._load_forecast(weather);
    }
    // update the display with the latest data
    deskletObj.displayForecast();
    deskletObj.displayCurrent();
    deskletObj.displayMeta();
  });
},

After making these changes, I received the error message unexpected token: '{'

I am seeking guidance on the correct JSON syntax for the code to properly handle the API URL.

Update - Based on feedback, I made the following adjustments:

The updated code looks like this

function apiurl() {
    let apiurl = this._baseURL + '=' + (this.apikey);
    str = str.replace('=','');
    console.log(str); 
}

Here are the log file results after running the code:

info t=2024-01-30T10:18:19Z bbcwx (instance 34): refreshing forecast at 10:18:19
error t=2024-01-30T10:18:19Z this is undefined
info t=2024-01-30T10:18:19Z Loaded desklet <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385a5a5b4f4078575953154f57575c165b57164d53">[email protected]</a> in 65 ms

Following advice from 3limin4t0r, I implemented the following updates:

function weatherApiURL {
    weatherApiUrl.path = "https://api.weather.com/v2/pws/observations/current?stationId=MyStationId&format=json&units=e&apiKey=MyApiKey"
    weatherApiUrl.toString()
    console.log(str); 
   }
   this._getWeather(weatherApiURL(), function (weather) {
   if (weather) {
    this._load_forecast(weather);
   }
   // update the display with relevant data
   deskletObj.displayForecast();
   deskletObj.displayCurrent();
   deskletObj.displayMeta();
   });

   },

Answer №1

If you're looking to retrieve the API URL using the apiurl() function and then pass it to _getWeather, here's one way to do it:

const generateApiUrl = () => {
  let url = this._baseURL + '=' + (this.apikey);
  url = url.replace('=', '');
  return url;
}

let result = this._getWeather(generateApiUrl(), (weather) => {
  if (weather) {
    this._load_forecast(weather);
  }
  deskletObj.displayForecast();
  deskletObj.displayCurrent();
  deskletObj.displayMeta();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to update the color of the mat-dialog-title using the material theme

Currently, I am utilizing the Angular Material Dialog and have been attempting to dynamically change the title color of the dialog based on the material theme. <h1 mat-dialog-title color="primary">{{ title }}</h1> Even though setting ...

Interacting with AWS SQS message generated by S3 using Python

When a file gets uploaded to S3, I find it useful that S3 can generate a message in SQS. However, retrieving the file name ("key":"filename.txt") from the dictionary structure in the SQS message body using Python proves to be a bit challenging due to the p ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

Incorporating the parent object into a nested JavaScript function

I have come across similar questions, but my situation seems unique to me. I have simplified my code and turned one line into a comment, but the core concept remains unchanged... function myFunction(options) { var button; options.widgets.forEach(f ...

Submitting a Yii 2 form automatically when it loads

Pjax::begin(); $form = ActiveForm::begin(); echo $form->field($model, 'testdata', [ 'inputOptions' => [ 'class' => 'form-control input-xsmall input-inline' ], ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

What is the best way to show "no results found" message in a jQuery search list?

Everything is working smoothly. Does anyone have any suggestions on how to display a message saying "No results found"? This is the code I'm using: http://jsfiddle.net/UI_Designer/8p426fog/4/ $(".my-textbox").keyup(function() { var val = $( ...

How can I add text to an HTML5 SVG similar to using the HTML5 <p> tag?

I am currently working on creating dynamic rectangular boxes and I am facing some difficulties with inserting text into the shapes. The SVG text requires setting x and y coordinates in separate text tags, and doesn't have built-in width and height pro ...

Update Input field by eliminating white spaces using jQuery version 3.2.1

I am currently developing an HTML/PHP form for user registration. Using the code below, I have managed to prevent any blank spaces from appearing in the input field: <!DOCTYPE html> <html> <head> <script> function stripspaces( ...

Images set as the og:image on the following 14 websites hosted on Vercel require authentication to be displayed

After deploying my Next.js 14 site on Vercel, I placed opengraph-image.png in the app folder alongside layout.tsx. Upon inspecting the meta tag, I noticed the following: <meta property="og:image" content="https://ns-website-6pnvd8ili-mare ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

What is the best way to create a placeholder for a select option with a looping value?

I have successfully implemented loops for the select options, but I needed to add a placeholder. In other words, I wanted the first value of the select options to be a placeholder, followed by the values generated from the loop. Here is the code that I u ...

Upon initiating a fresh project with npm create vite@latest and proceeding with npm install, an error message promptly surfaces

semver <7.5.2 Severity: moderate Potential vulnerability in semver due to Regular Expression Denial of Service - https://github.com/advisories/GHSA-c2qf-rxjj-qqgw A fix is available by using the command npm audit fix --force Running this may install [e ...

Enhanced functionality in MUI TablePagination now allows users to easily select their desired page

I've implemented MUI TablePagination to enable pagination in my table. The code is performing well, offering most of the features I need: Users can choose between displaying 5, 10, or 20 entries per page using a dropdown. The number of pages displaye ...

Text input fields failing to record text

I've set up a forum using react-redux and material ui, but I'm facing an issue where the text fields are not updating based on state changes. When users try to type in the text field, nothing seems to happen. onChange={e => onT ...

Adjust the JSON format that is retrieved from an Ajax call

I am working with a JQuery plugin that includes the following code snippet: transformResult: function(response, originalQuery) { } Within this function, I have the task of converting Json data from the originalQuery to the response format: [ { "Id": ...

Exploring Sencha Touch: Unveiling the Inner Elements of Nested JSON Structures

Hello everyone, I am facing a challenge with Sencha Touch and could really use some assistance. My goal is to display a list of children's text using the JSON data provided below along with my Sencha Touch code snippet. While I have explored the API a ...

How can we format a number to match the Brazilian number system while still maintaining its ability to be used in calculations?

Is there a known method to convert the number 123,123,214.93 into Brazilian currency format (123.123.214,93) for display purposes only? I attempted to achieve this conversion using a JavaScript function where I added periods after every 3 numbers and repl ...

What is the process of transferring data from one div to another div (table) using AngularJS?

In my quest to enhance my table with JSON data upon clicking the + icon, I am faced with two sections: Pick Stocks where stock names and prices (retrieved from data.json) need to be added to the table found in the Manage Portfolio section. First Section h ...