Parsing JSON responses into arrays in JavaScript

Seeking help to convert an AJAX JSON response into a JavaScript array. I have tried using split but it didn't yield the desired result. Any assistance is appreciated!

The AJAX JSON response (in a single string) is as follows:

Array[Date:"[['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]]"]

My goal is to transform this into the following array:

var array = [['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]];

Answer №1

Utilize regular expressions to extract information from the given string.

let text = `Array[Date:"[['2016-09-09',162], ['2016-12-04',145], ['2017-01-11',130]]"]`;

// regular expression for desired pattern
let regex = /\[\s?'(\d{4}-\d{1,2}-\d{1,2})'\s?,\s?(\d+)\s?\]/g;
// array to store results
let results = [],
  // variable to cache matches
  match;

// loop through the matches
while (match = regex.exec(text)) {
  // add values to the array
  results.push([match[1], +match[2]]); // use + sign to convert to number
}

console.log(results);

Explanation of the Regular Expression here


Just a heads up: It is recommended to update the backend code to produce a valid JSON string (easily achievable in all programming languages with predefined functions or libraries).

Answer №2

To convert a string AJAX response into an object, simply use the JSON.parse(strResponse) method.

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

Encountering the error "Cannot access property 'stroke' of undefined" when utilizing constructors in React and p5

Hi there, I'm having trouble with my React code and could really use some assistance. Being new to React, I'm trying to create a collision system between multiple bubbles in an array, but I keep running into this undefined error: https://i.sstat ...

Steps to activate a Controller method in ASP.NET MVC 4 using an ajax call

This query marks my debut on SO, so bear with me if it's a bit basic. I've set up a button to trigger a method in the Controller through an ajax request. However, I'm encountering a tricky error message: "The message cannot be deserialized ...

Authentication in JavaScript using JSON strings: two objects are being authenticated

Currently, I am in the process of authentication using $.ajax({ type: "GET", url: urlString, async: false, beforeSend: function(x) { }, dataType: "json", username: "<a href="/cdn-cgi/l/email-protection" class="__c ...

Using jQuery to generate columns depending on the quantity of occurrences of an element inside a specific Div

I've encountered a challenge while using a plugin that restricts access to the HTML, but allows for adding CSS and Javascript. I am aiming to achieve the following: Determine if a specific class within a div is active If it's 'active' ...

No errors detected when utilizing bcrypt-node for callbacks

I have developed a node library file named encrypt.js. Inside this file, there are functions created using bcrypt-nodejs var bcrypt = require('bcrypt-nodejs'); exports.cryptPassword = function(password, callback) { bcrypt.genSalt(10, f ...

Choose an image depending on the title, but only if a specific condition is met

var no_images2 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images2).css('pointer-events','none'); var no_images3 = $j("img[title^='Click to enlarge image no_photo']").parent(); $j(no_images ...

Transitioning from using lerna to adopting pnpm

We are in the process of transitioning our project from Lerna to PNPM and we currently have a script that we run. Here are the commands: "postinstall": "npm run bootstrap" "bootstrap": "lerna bootstrap --hoist", &quo ...

Encountering an issue with AngularJS where the controller is not being registered when combining ocLazyLoad and ui-router

Struggling with implementing ocLazyLoad in my project, I keep encountering this Angular error Error: $controller:ctrlreg A controller with this name is not registered The 'eventoCtrl' controller is not registered. NOTE: Utilizing ui-router f ...

Managing dynamic input texts in React JS without using name properties with a single onChange function

Dealing with multiple onChange events without a predefined name property has been challenging. Currently, one text input controls all inputs. I have come across examples with static inputs or single input functionality, but nothing specifically addressin ...

Converting an Array with Key-Value pairs to a JSON object using JavaScript

After using JSON.stringify() on an array in JavaScript, the resulting data appears as follows: [ { "typeOfLoan":"Home" }, { "typeOfResidency":"Primary" }, { "downPayment":"5%" }, { "stage":"Just Looki ...

Get the initial item from a Nested Array in JSON using NodeJS

I am attempting to extract the nested array named platforms, but I am specifically interested in only the first key within that array. So, for the Array it should look like [{platforms: [windows], [windows]]} instead of [{platforms: [windows, osx, linux, n ...

Display remains stagnant and does not refresh

I have a view structured like this: <div class="container content-sm"> @{ if (Request.IsAuthenticated) { <a>my profile</a> } else { if (Request.Url != null) ...

Is there a way I can conduct a search that includes both uppercase and lowercase characters simultaneously?

My current task is to create a search function that can search for elements in both lower and upper case, regardless of the case typed in by the user. I have attempted to implement a search feature that covers both upper and lower case scenarios, but it s ...

Expandable menu using jQuery

Currently, I am experimenting with an Accordion Menu plugin called example 3: Non-accordion (standard expandable menu). My goal is to set up a menu structure where there are 5 options. Two of these options have sub-menus, while the other three are direct ...

Chrome is the only browser that will experience a failure in a CORS request if it includes

When attempting to make a simple CORS request to an external application server that uses a session key for authorization, I encountered some issues. $.ajax({ type: "GET", url: "https://192.168.1.72:8442/api/file/", headers: {"Authorization": ...

Making an Ajax call without using the push.js library

I'm currently utilizing Ratchet 2 for my application development. I am attempting to implement a basic ajax request and retrieve the response as shown below: function attemptLogin() { var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpReques ...

How do I link JavaScript with a database in Django?

I am currently working on a project using Django and I'm looking to integrate js into it. While I don't have much experience with js, I am interested in learning how to manipulate the database using js. Specifically, I want to implement a delete ...

Exploring the Efficiency of Multidimensional Arrays Compared to Flat Arrays

Are there any performance issues with using either of the methods below? Which one is faster, if any? It would be beneficial to have some performance tests conducted. Multidimensional array: // Using multidimensional array: int ****multidim_arr; // ... i ...

Issue with JQuery Ajax duplicating entries

What is the purpose of my inquiry? I am currently attempting to utilize jQuery's ajax function to insert data into a MySql database by invoking a PHP script. What issue have I encountered? The data is being duplicated in the database upon inse ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...