What is the best way to convert a JSON string from a specific array into an array object?

JSON object:

{
    "data": {
        "myStatus": "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]"
    },
    "success": true
}

Upon converting to the JSON object, it appears that the myStatus is being treated as a string. The goal is to parse it as an Array instead.

Typically, the JSON object should look like this:

var jsonObj= JSON.parse(<abovestring>);
jsonObj.data.myStatus[0] => [1 2 21 0 50 0 0 0];
jsonObj.data.myStatus[0][0] => 1
jsonObj.data.myStatus[0][1] => 2
jsonObj.data.myStatus[0][2] => 21

Is there a way to split it in the required format?

Answer №1

To achieve this, you can utilize the String#split method in combination with Array#map:

let str = "[1 2 21 0 50 0 0 0],[2 1 3 1 50 0 0 0]";
let arr = str
  .split(',')
  .map(item => item.slice(1, -1))
  .map(item => item.split(' '));

console.log(arr);

Nevertheless, this approach may not be the most elegant and could lead to errors if there are changes in the string structure. It would be advisable to address the root issue by correcting the JSON format instead.

Answer №2

When the list is enclosed in quotation marks, JSON.parse interprets it as a string because that's what it actually is.

To convert it into a valid array, you can remove the quotation marks, encapsulate the list with [] square brackets, and separate elements with , commas like this:

{
    "data": {
        "myStatus": [[1, 2, 21, 0, 50, 0, 0, 0], [2, 1, 3, 1, 50, 0, 0, 0]]
    },
    "success": true
}

If you're unable to modify the JSON string and it must have a string for data.myStatus, then an extra step is needed to manually parse it. For example:

var string = jsonObj.data.myStatus;
string = `[${string}]`;
string = string.replace(/ +/g, ',');
jsonObj.data.myStatus = JSON.parse(string);

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

What is the best strategy for managing pagination when dealing with a large number of pages?

Up until now, I have understood that pagination only links different pages together. This works fine when dealing with a limited number of pages or posts to display. However, what if I have 30 or more pages to paginate? Wouldn't it be impractical to c ...

Sorting dictionary items without using lambda functions

Seeking a different approach to sorting without incorporating lambda: sorted(dict.items(), key=lambda i: -i[1]) My attempts using the operator module have not yielded the desired results. ...

Unable to integrate bootstrap with webpack

Incorporating Express, Webpack, and Bootstrap. Currently utilizing css-loader for my stylesheets. Below is the contents of my webpack.config.js: const path = require("path"); config = { "entry": "./modules/entry.js", "output": { "path": p ...

Error message: Angular encountered a SyntaxError when parsing JSON data due to an unexpected character at the beginning of the data

Encountering SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data After validating the JSON, it was discovered that the error lies in: let json = JSON.stringify(user); let params = "json="+json; // The error se ...

The boxslider plugin is malfunctioning when accessed in Sitecore's preview mode

Even though the Boxslider plugin works when we view the page in a browser, it fails to function properly when the same page is viewed in Sitecore's Preview mode. This issue can be replicated by navigating to Presentation in the top menu, then selectin ...

Getting an array of php data through ajax instead of using responseText in my javascript code

I am currently facing an issue with my ajax setup. My page, which contains JavaScript, calls a PHP file and receives data through xhttp.responseText. While this method works fine for handling strings, it struggles when I pass a JSON encoded array. The resp ...

When onSubmit is triggered, FormData is accessible. But when trying to pass it to the server action, it sometimes ends up as null

I am currently utilizing NextJS version 14 along with Supabase. Within my codebase, I have a reusable component that I frequently utilize: import { useState } from 'react'; interface MyInputProps { label: string; name: string; value: stri ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Running JavaScript in selenium and obtaining the result

I'm currently utilizing JavaScript with Selenium WebDriver. Here is a snippet of my code: let return_value = driver.execute_script(script) However, I am unsure how to retrieve the value from my script. const token = await grecaptcha.enterprise.exec ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

Optimal Approach for Processing JSON Data in Laravel

Currently, I am using Laravel 5.5 and PHP 7 to develop a form similar to this. <form id="form" name="xxx" action="post"> <input type="text" name="body_color[1][en]"> <button type="submit" name="submit">Submit</button> </form ...

How to apply unique styles to multiple elements with the same class using jQuery?

How can I add different classes to multiple div elements with the same class based on their content? <div class = "flag"> Yes </div> <div class = "flag"> No </div> <div class = "flag"> Yes </div> <div class = "flag"& ...

What is causing the table to not be displayed in this Javascript program when it is used in a

I am currently experimenting with incorporating an infinite loop before the prodNum and quantity prompts to consistently accept user input and display the output in a table. Although the program is functional when executed, it fails to showcase the table ...

Tips for generating dynamic JSON: Organize the data by filtering it and creating key-value pairs for the appropriate JSON objects

How can I generate dynamic JSON based on input, filter data, and create appropriate key-value pairs for JSON objects? The database schema can be viewed https://i.sstatic.net/iP1JS.png Although I attempted the following code, it did not produce the desi ...

Issue with the display of Google reCaptcha verification popup within Mat Dialog

While working on an angular material dialog form, I integrated Google reCaptcha. However, when the reCaptcha verification popup appears, it displays above the form as shown in the image. https://i.sstatic.net/ax8QN.jpg I noticed that every time the mat d ...

Maximum opacity in Three.js fog

My Current Endeavor: I am in the process of developing a lightweight GIS application with topography. One feature I want to implement is atmosphere haze. The Code I'm Working With: (Please bear with me as I have multiple scenes) fogColor = new T ...

Activate a button by simulating a click event through a shortcut key with the help of a

I have incorporated the hotkeys plugin to enable shortcut functionality on my website. Currently, I am looking for a way to automatically trigger a button click when any shortcuts are pressed. hotkeys.add({ combo: 'alt+1', callback: function (da ...

What steps should I take to ensure that the buttons on my restaurant website are correctly displaying the overlays?

I'm currently facing an issue with the functionality of the buttons on my React.js-powered restaurant website. These buttons are located within a component called MenuButtons.jsx and are situated at the bottom of a shorter menu section on the homepage ...

Having trouble sending Props between components within a specific route as I keep receiving undefined values

Here is the code for the initial component where I am sending props: const DeveloperCard = ({dev}) => { return ( <Link to={{pathname:`/dev/${dev._id}`, devProps:{dev:dev}}}> <Button variant="primary">Learn More</Butt ...

Node.js array push operation malfunctioning

let retrievalQuery = "SELECT cp.*,ud.user_id,ud.firstname,ud.lastname,ud.displayname,ud.profile_pic,c.challenge_name from `challenge_post` as cp INNER JOIN `user_details` as ud ON cp.challenge_user_id = ud.user_id INNER JOIN `challenge` as c ON c.id = ...