Error: Unable to iterate over JSON data as json.forEach is not a valid function

let schoolData = { "name": "naam", 
    "schools" : [
        "silver stone"  , 
        "woodlands stone"  , 
        "patthar"
    ],
    "class" : 12 }

schoolJSON = JSON.stringify(schoolData) ; 
let jsonData = JSON.parse(schoolJSON) ; 

jsonData.forEach(element => {
     console.log(element.schools) ; 
});

I am attempting to display the names of schools, but encountering an error:

" Uncaught TypeError: json.forEach is not a function "

Seeking assistance in resolving this issue.

Answer №1

When using the forEach method, it is important to note that it only works on array-type data.

let myJSON = {
"name": "naam" , 
"schools" : [
     "silver stone"  , 
     "woodlands stone"  , 
     "patthar"
], 
"class" : 12}

let info = document.getElementById("info"); 
let clickme = document.getElementById("clickme");
 
myJSON = JSON.stringify(myJSON) ;
/* "json" variable has an object type data */
let json = JSON.parse(myJSON) ; 

// The For Each function can only be used on arrays.
// It cannot be directly applied to loop through an object
json.schools.forEach(e => {
     console.log(e) ; 
});

Therefore, if you want to iterate through the school array within json.schools, you should use forEach on "json.schools", which is an Array, rather than on the "json" variable containing object data.

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

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

Ways to increase the values in a textbox

My task involves handling checkboxes that are populated with data from a database. The goal is to have certain checkboxes pre-checked based on the retrieved data, and if any are not checked, their values should be entered into a textbox. For instance, con ...

Ways to convert a JSON string to Long, Double or Number

I'm dealing with a JSON structure similar to this: { "id_document" : "12345679", "name" : "John SMmith", "value" : "127,30" } My goal is to convert the "value" field into a Double/Number type, like so: { "id_document" : "12345679", "name" : "John S ...

Escape from the abyss of callback hell by leveraging the power of Angular, HttpClient, and

I'm currently grappling with understanding Angular (2+), the HttpClient, and Observables. I'm familiar with promises and async/await, and I'm trying to achieve a similar functionality in Angular. //(...) Here's some example code showca ...

Is there a method to adjust the styling of my <header> once the page hits a specific #anchor point?

Seeking some assistance with a website design challenge I am facing. I am currently working on a one-page portfolio site with four #anchor points that serve as "pages". Each div has a height of 100% to fill the entire browser height. The header, which co ...

Repairing the toggle feature using a pair of buttons

I am looking to make changes to my code so that when a button is clicked twice, it reverts back to its original state. Additionally, is there a way to have neither gender button selected upon page load? If you want to see the code in action, follow this l ...

React Material UI DataGrid: Error encountered - Unable to access property 'useRef' due to being undefined

The challenge at hand Currently, I am faced with a dilemma while attempting to utilize the React DataGrid. An error in the form of a TypeError: Cannot read property 'useRef' of undefined is appearing in my browser's stack trace. https://i.s ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...

Looking to transfer JSON data between JavaScript and Java code

I am dealing with a JSON string within my JavaScript code and I want to pass this information to a Java class. Can I simply use a regular Java class for this task or is it necessary to implement a servlet? Furthermore, I am curious about the process of pa ...

When using the dict update method in SQLAlchemy, how does it affect the Object-Relational Mapping (ORM

Recently, I encountered an issue with a SQLAlchemy Table that had a JSON column: from sqlalchemy.dialects.postgresql import JSON class MyTable(db.Model): id = db.Column(db.Integer, primary_key=True) my_json_column = db.Column(JSON) My attempt to ...

Having trouble choosing an option from the dropdown menu with Puppeteer Js

I need help with Puppeteer JS to select the initial element in a dropdown. Any suggestions? Once I input the city name in the text field, I want to choose the first option from the dropdown menu. const puppeteer = require('puppeteer'); (async ...

I'm having an issue with my Bootstrap tabs - they seem to be unresponsive when clicked

I've been working on a Bootstrap website and have run into some issues that I can't seem to resolve. One problem I encountered was with a set of tabs that were supposed to be interactive, but for some reason, they weren't working as expected ...

Showing information in Vue.js using v-for loops

I'm currently working on a basic shopping cart system using Laravel and Vue.js. I've been able to add items to the basket and retrieve them successfully up to a certain point, but I'm facing challenges when it comes to displaying these items ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

Creating a hash from a string in Javascript

I'm struggling with the process of converting a string into a nested hash in JavaScript. Here is the string I want to convert: "{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cn ...

Issues with functionality arise when cloning HTML divs using JQuery

VIDEO I created a feature where clicking a button allows users to duplicate a note div. However, the copied note does not function like the original - it's not draggable and changing the color of the copied note affects the original note's color. ...

Maintaining consistency in the representation of foreign keys in input/output for a RESTful JSON API

I'm exploring the realm of creating a non-XML API for the first time, and I have some inquiries regarding how to effectively represent connected resources throughout the API. Let's delve into this scenario using a user resource and its associated ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Having trouble creating a polygon from JSON in ESRI ArcGIS Javascript framework?

Can anyone assist with understanding the issue of trying to draw a polygon using the ESRI ArcGIS Javascript API? The image, JSON string, and code snippets provided below outline the code, console output, and expected behavior. Any help would be greatly app ...

Transact-SQL: Array of JSON

I am trying to save the output of an API query in JSON format to a SQL Server 2016 table. Currently, I am having trouble transforming the JSON output. Here is what I have tried: When I execute this code: DECLARE @J NVARCHAR(MAX) = '{"c":[4. ...