Converting JSON data into an array using JavaScript

Stored in a variable named "response", I have the JSON value below:

{"rsuccess":true,"errorMessage":" ","ec":null,"responseList":[{"id":2,"description":"user1"},{"id":1,"description”:"user2"}]}

var users=response.responseList; 
var l = users.length;

However, this code results in an error.

[Error] TypeError: undefined is not an object (evaluating 'users.length')

Answer №1

Once you have received the response from the callback function, you will need to transform the JSON string into an object by utilizing

JSON.parse(response);

Answer №2

It seems there is a syntax error in this line that you might have missed

[{"id":2,"description":"user1"},{"id":1,"description”:"user2"}]}

The double quote around the description identifier is not closed properly. Simply adjust it to:

{"id":1,"description":"user2"}

Once you make this change, everything should work correctly

Answer №3

Variables that are undefined do not function as objects, and therefore do not possess properties like length.


You have yet to change your JSON data into an object.

To do so, utilize the following code:

var obj = eval("(" + json + ')');

The eval() function runs the code provided and generates a native JavaScript object.

However, many individuals critique the use of eval() when handling unsanitized input.

Your safest option is to employ the native JavaScript method: JSON.parse(jsonString);, which was specifically designed for parsing JSON data and converting it into an object.


Access more information on JSON parsing here

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

Activate and focus on the text input field with a checkbox using AngularJS

Currently, I have a Bootstrap 3 input field with some prepended content along with a checkbox. My goal is to have the input field disabled until the checkbox is checked, and when it is checked, I not only want to enable the field but also set the focus on ...

Implement a callback function in React using hooks after changing the state

Back in the days of React before hooks, setting state and calling a function after it had been set was achieved using the following syntax: this.setState({}, () => {//Callback}) Now, with hooks, what is the equivalent way to achieve this? I attempted ...

Seeking a method to attach information from a div to a hyperlink

As a complete novice in the world of CSS websites, I find myself struggling to accomplish what seems like a simple task. I am working with an automatically generated CSS/JavaScript website where on the "individual" page, a person's name is listed with ...

Using Jmeter's JSON Extractor for parsing response and extracting token value

Currently facing an issue with extracting the "webToken" response. I have attempted using both $..webToken and $.webToken as JSON path expressions, but no luck so far. Any suggestions on how to correctly extract this information? This is for use in JMete ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...

What is the process of creating and customizing popovers in Bootstrap 5 with jquery?

Is there a way to dynamically create and add content to Bootstrap 5 popovers using JavaScript or jQuery? In Bootstrap 3, I used the following method: $('#element').popover({ placement : 'left', trigger : 'focus', html: true } ...

Choose a random element from a string with Javascript

Could someone please help me figure out why my code isn't functioning as expected? I'm trying to randomly select three names from a list and ensure that no name is repeated. While I believe I am on the right track, something seems to be missing. ...

retrieving values from an array in ng-model and displaying them within <input

I am seeking assistance with retrieving values from an array and formatting them into a comma-separated list. Visit this link for reference Within my input tag: <input type="number" ng-model="data.price1[$index]" ng-change="pricecalc1($index)" placeh ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

Transform the Nodejs server into a reusable Node module

Can a nodejs API server be transformed into a node module for use in other projects with minimal code modifications? Additional Information: The node js server contains various APIs (get, post, put). If I integrate this server as a node module within anot ...

What is the most effective way to decode a JSON formatted multidimensional array of checkboxes?

Uncertain if the Title was accurate, the actual application is a quiz. Let me provide an example with this sample snippet. <form method="POST"> Softdrinks: <div class="checkbox"> <label><input type="checkbox" ...

How can I sync changes between two variables in node.js?

Is there a method to create a shared variable in JavaScript? Here is an example of what I am attempting to achieve: var id = 5; var player = new Player(id); var array1[0] = player; var array2[0] = player; array1[0].id = 8 console.log(array1[0]); // ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

Having trouble with the image compressor not being imported correctly in Next.js?

I've been attempting to compress an image, but when I try to import the ImageCompressor normally like this: import ImageCompressor from "image-compressor.js"; It throws an error: Uncaught ReferenceError: window is not defined This is the s ...

zend_json is a structured data format that consists of an array composed of

Imagine I have the following scenario: $arr = array(some object with property a,b,c,d,etc); When you use Zend_Json::encode($arr); Rather than encoding the object within it as well, it simply returns an encoded empty array: [{}] This situation can be de ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

Restricting href Usage Based on Session

I find myself in a challenging situation without a clear solution at hand. Within this code, I am utilizing a link and a button for which I need to save the page in a database. Therefore, creating a server control is not an option as it will not be render ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

php array modification

Is there a way to make this array more user-friendly and easier to work with? Here is the current structure: $res = [ "DATA DOCUMENT:",                 "Countrydocument: CO",                 "Person type: Na ...