Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file.

Here is an example of my JSON data:

{"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}  
{"sarah":{"styleName":"sarah","fillTrans":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}
//....

Below you can see the JavaScript code I have written for this purpose.


let dropdown = document.getElementById('tem');

dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Template';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const url = '../../templates.json';

fetch(url)  
  .then(  
    function(response) {  
      if (response.status !== 200) {  
        console.warn('There seems to be a problem. Status Code: ' + 
          response.status);  
        return;  
      }

      response.json().then(function(data) {  
        let option;
        console.log(data);
        for (let i = 0; i < data.length; i++) {
          option = document.createElement('option');
          option.text = data[i].styleName;
          dropdown.add(option);
        }    
      });  
    }  
  )  
  .catch(function(err) {  
    console.error('Fetch Error -', err);  
  });

Despite receiving a 200 response, I keep encountering the following error and the dropdown menu remains empty: Error:

Uncaught (in promise) SyntaxError: Unexpected token { in JSON at position xxx
Promise.then (async)
(anonymous) @ VM8493:22
Promise.then (async)
(anonymous) @ VM8493:13

The select element for the dropdown looks like this:

<select id="tem" class='w150'>
</select>

Answer №1

 substitution: option.text = data[i].styleName; modification: let keys=Object.keys(data[i]) with option.text = data[i][keys[0]].styleName 

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

Best method for choosing elements of an array using values from a separate array in Python?

My dilemma involves managing two arrays, specifically labels and distances: labels= array([3, 1, 0, 1, 3, 2, 3, 2, 1, 1, 3, 1, 2, 1, 3, 2, 2, 3, 3, 3, 2, 3, 0, 3, 3, 2, 3, 2, 3, 2,...]) distances = array([2.32284095, 0.36254613, 0.95734965, 0.3542 ...

What are the typical situations in which Node.js is commonly used?

Do you believe that a majority of node.js users primarily utilize npm? What do you think are the most prevalent use cases for node.js apart from npm? ...

Looking for a solution to the problem: Module 'import-local' not found

internal/modules/cjs/loader.js:596 throw err; ^ Error: Cannot find module 'import-local' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modules/cjs/loader.js:520:25) Encoun ...

Creating a Nested JSON Object in Python

To achieve the desired JSON output format shown below, I am struggling to correctly nest the 'number' object under 'items'. { "items": [ "number": { "value": 23, "label": test } ] } Wh ...

Filter an array of objects based on a provided array

I have an array of objects that I need to filter based on their statuses. const data = [ { id:1, name:"data1", status: { open:1, closed:1, hold:0, block:1 } }, { id:2, name:"data2", ...

Is it possible to utilize the output of a function to determine the styling of a div element in Vue?

Hi, I'm trying to use the v-bind:style in my div to apply the textposit function with the textpos prop as a parameter. The function should adjust the style of the div based on the value of the parameter. <div class="container" :style=&qu ...

Troubleshooting issue: JSON.stringify function returning 'undefined'

Having some trouble with JSON in JavaScript. I've been using JSON.stringify without issue until now. But suddenly, when I try to use it in my application, I keep getting this error in the console (Google Chrome): Uncaught TypeError: undefined is not ...

Retrieve information from an array of objects by utilizing a separate array

There are two separate arrays provided below: ages = [20,40,60]; doctors = [{ "name": "Moruu", "age": 18, "sex": "Male", "region": "Africa" }, { "name": "Khol ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Can you identify the HTML table format and suggest effective web scraping methods?

I have been attempting to retrieve data from the following link, http://www.rchsd.org/doctors/index.htm? strt = 0 & ln = & fn = & sp = & grp = & loc = & lng = & gen = , using R but finding it quite challenging. I have observed that the URL remains constan ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

Move a div by dragging and dropping it without creating duplicates

I'm in need of some assistance. It seems like a simple task, but I'm having trouble finding a solution. I've managed to create draggable elements that work smoothly without any issues. The drag and drop functionality is working perfectly. ...

Eliminate redundant values by comparing multiple dictionary lists in Python

I currently have two large lists of dictionaries containing data. Here are the examples: a= [{'name':'A','color':'1'}, {'name':'B','color':'2'}, {'name':'C ...

Gaining access to the isolated scope of a sibling through the same Angular directive led to a valuable discovery

I am currently working on an angularjs directive that creates a multi-select dropdown with a complex template. The directives have isolated scopes and there is a variable called open in the dropdown that toggles its visibility based on clicks. Currently, t ...

Verify whether a specific value is present in an array (Laravel or Php)

I have the following array: $list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere'); When I use die() + var_dump() on this array, it returns: array:2 [▼ 0 => "hc1wXBL7zCsdfMu" 1 => " ...

What is the process for integrating custom fields into a product using Stripe, and how can a stock limit be implemented for each customized field?

Currently, as I develop an ecommerce website using Next.js and integrate Stripe for checkout, I've come across the feature of custom fields in Stripe. This feature allows me to add options such as small, medium, and large for clothing sizes. However, ...

I am having difficulty converting a Json file into a java object using Gson

My Json file contains information about an airport: { "airports": [ { "fs": "VGO", "iata": "VGO", "icao": "LEVX", "name": "Vigo Airport", "city": "Vigo", "cityCode": "VGO", "stateCode": "SP", "countryCode": "ES", "countryName ...

Is there a way to recover a deleted element from an array?

I have a list of user cards, and my task is: Clicking the "undo" button: will restore the last card that was deleted (using an array) Question 1: How can I create an array from the displayed cards list? Question 2: How do I restore the last deleted card? ...

Tips for transferring information from a parent to a child controller in Angular using the $broadcast method?

I am trying to send an id argument to a child controller using Angular's $broadcast method, but despite my best efforts with the code below, I can't seem to make it work. Any suggestions on what might be incorrect in my implementation? ParentCtr ...

Changing the display value/color of a td element using JSON data

I have been working on an application that retrieves JSON data through an Ajax call. This JSON data contains objects with different status codes for each extension (1 = online, 2 = ringing, 3 = busy). My question is how can I convert these numerical value ...