Looping through a JSON array in JavaScript retrieved from a MySQL database

My data is originally stored in a MySQL database in the following format...

{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}

When I retrieve it as JSON through Express, it appears like this...

[{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]

This JSON structure has been validated on JSONLint.com.

The challenge arises when trying to iterate over this data using JavaScript in HTML...

Here is my current JavaScript code....

   fProfiles_JSON = JSON.parse(xhr.responseText);
   console.log('Type of '+ typeof fProfiles_JSON); //results in "object"
   console.log('My object', fProfiles_JSON);
   console.log('LENGTH ', fProfiles_JSON.length); // Returns "1"

I understand that I need to find a way to loop through this object to access the values for "profile" and "count", but I'm unsure how to proceed due to the length being "1". I realize this may be a simple solution that I am overlooking. Can anyone provide guidance on where to start?

Answer №1

let data = [{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]

// To extract the string in this scenario:
let jsonString = data[0]["JSON"];
let parsedProfiles = JSON.parse("[" + jsonString + "]");
// It was noted that the content of the string is not valid JSON,
// so square brackets are added at the start and end to create a list
// of objects.
parsedProfiles.length // should be 3
// You can then access the `count` and `profile` attributes.

Answer №2

When working with JSON, it's important to note that single quotes are not accepted and must be replaced.

//xhr.responseText contents simulated with var
resp = "[{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22}"}]";

j = JSON.parse(resp);
inner = j[0]['JSON'].replaceAll("'","\"");

objs = JSON.parse("[" + inner +"]");
objs[0]

Result:

Object { profile: "sweet", count: 38 }

It is worth noting the caution advised by @barmar about using a custom parser to manipulate JSON data.
A more refined approach would involve using specific regular expressions to replace single quotes.

# added possible 'key': 'value' at the end
resp = "[{"JSON":"{'profile':'sweet', 'count':38},{'profile':'bitter', 'count':31},{'profile':'green', 'count':22},{'key99': 'value99'}"}]";
j = JSON.parse(resp);

re3 = /[{]'/ig;
re4 = /'[}]/ig;
re1 = /'(, *|: *)'/ig;
re2 = /' *: *([0-9])/ig;
inner = j[0]['JSON'].replaceAll(re3,"{\"").replaceAll(re4, "\"}").replaceAll(re1, "\"$1\"").replaceAll(re2,"\":$1");

objs = JSON.parse("[" + inner +"]");

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

Exploring the Unpredictable Results of Recursive Functions in JavaScript

Take a look at this recursive code snippet. function calculateFactorial(n) { if (n === 0 || n === 1) { return 1; } else { console.log(calculateFactorial( (n - 1) )); return n * calculateFactorial(n - 1); } } const num = ...

How to use Angular 8 HttpClient to set JSON headers

When I attempt to send a JSON object using Angular 8 HttpClient to an ASP.net Core backend, the following code is used: import { HttpClient, HttpHeaders} from '@angular/common/http'; import { User } from '@/_models'; login(usernam ...

Tips for retrieving reverse geocodes using PHP cURL and JSON:

How can I echo only the formatted address from a JSON response using PHP? Here is the code I currently have: <?PHP $ch = curl_init(); $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=22.569794,88.357934'; curl_setopt($ch, CUR ...

Encountering a problem with Axios get request error in React and Redux when communicating with a Laravel 5.2 API

Currently, I am utilizing react alongside redux and axios for handling asynchronous actions. The backend is powered by Laravel 5.2 API which is located on a subdomain, while React resides on the main domain. However, whenever I attempt to make an async GET ...

What is the best way to sequentially read various sections of a file in vue.js?

I am currently working on a browser tool that analyzes a large file and provides statistics based on its content. The tool randomly selects k parts of the file for processing, treating each part individually. As each part is processed, an object is update ...

Using a Function as an Argument for a Promise in NodeJS

Being new to Node and not having much experience with front-end web development or Javascript, I am encountering some errors while attempting simple front-end tasks. Despite reading various sources on the errors, I have not found a clear solution. I have a ...

Customizing a thumbnail script to dynamically resize and display images according to their size properties

I am attempting to modify a simple JavaScript script that enlarges an image from a thumbnail whenever it is clicked. The issue I am facing is that the enlarged image is displayed based on a fixed width size. I want the enlarged image to be displayed accord ...

Is there a way to access the state value within the reducer function of createSlice?

Currently, I am utilizing redux-toolkit within my react project. A concern arises in a specific reducer inside the createSlice method where I aim to incorporate an existing array of entities from the state and then merge it with a new array before finalizi ...

Issue with jQuery: addClass not toggling within an IF statement

Is there a way to dynamically add the class "disable" to an anchor tag when a user selects the radio button labeled "Remove"? Currently, in the provided fiddle, the class is added as soon as the page loads. I have included code in the script that successf ...

What is the process for sending a PHP Post XML Request to the server for the TNT Express Connect Pricing module with appVersion 3.2?

TNT Express Connect Pricing module) was discussed in this post by @MackieeE. While the solution provided works for the 2.0 version of the TNT API, I am attempting to use the 3.2 version and encountering issues. The XML values being used are: <?xml vers ...

Is there a way for me to locate a forum using a JWT Token?

I am searching for a way to retrieve forums using JWT Token. If a user has created 3 forums, I want to display them in a list. My Request is structured like this : ### http://localhost:8080/forum/getByOwnerID Authorization: Bearer {{adminToken}} Alternat ...

Exploring the possibilities of integrating InApp functionality with node.js and

Currently, I am working on developing a mobile game server using node.js. Specifically, I have utilized Express and postgresql. In the process, two key questions have arisen: In this game, users have the option to purchase an In-App item that offers th ...

Using JavaScript to enable autocomplete functionality in an ASP.NET combobox

Is there any way to use JavaScript functions with the asp AJAX Toolkit autocomplete combobox? I'm looking for a way to select the selected item text or value on the client side. Thanks, Atif ...

Unable to perform multi-delete action upon clicking the checkbox button as intended

Within my GridView, I have implemented a Multi-delete feature. Below is the code snippet for your reference:- <script type="text/javascript> function ValidateAll() { var chkselectcount = 0; var gridview = document.getElementById( ...

What could be causing three.js to not function properly for me within the NetBeans IDE?

I have recently been experimenting with the three.js library in Notepad+ and Chrome, but now I want to transition to using it within NetBeans IDE. My attempt to import it into NetBeans by adding <script type="text/javascript" src="js/three.js"></ ...

Using Jquery to dynamically update input values during key events

I am encountering an issue with a select tag. When I use the keydown event to set a value from the dropdown options as follows: $(this).find("option[value='11']").attr('selected', 'selected') The dropdown is displaying 12 in ...

Generate a new JavaScript object and populate it with information

I am looking to create a JavaScript object in the following format: var CarList = {}; I then want to populate it using a for loop (retrieving data from a MySQL database) similar to this: for(var i = 0; i < result.length; i++) { CarList.Construct ...

Setting default custom messages for every field in Joi

Can default custom error messages be set for all fields? It can be tedious to set custom errors for each individual field. This is my current process: const email = Joi .string() .email({ minDomainSegments: 2, tlds: { allow: ['com', &apo ...

React component is being invoked prior to the completion of the fetch operation

In my React code, I am facing an issue with the fetch function not completing in time to pass data to the Chart component. As a result, the chart is rendered without any graph displayed. export const OverviewChart = () => { type dateValue = { x: n ...

Struggling with grasping the concept of promises in AngularJS

I encountered a challenge while working with AngularJS & REST. My data service was not returning data in time for my model to use, despite implementing a promise. I would greatly appreciate any assistance from those more knowledgeable on this matter. In ...