How can I convert a string into an array?

Is there a simple way to convert the following string into an array?

"[[0.01,4.99,0.01],[5,14.95,0.05]]"

I'm aiming for a result like this:

var x = [[0.01,4.99,0.01],[5,14.95,0.05]];

Answer №1

let numbers = JSON.parse("[[0.01,4.99,0.01],[5,14.95,0.05]]");

Alternatively, you can use jQuery for JSON parsing (which is preferred over using eval):

let numbers = (new Function("return " + "[[0.01,4.99,0.01],[5,14.95,0.05]]"))();

In order to fully support JSON.parse and JSON.stringify in older browsers, consider using a polyfill. I recommend using json3, as Crockford's json2 can be quite cryptic.

Answer №2

const data = JSON.parse("[[0.01,4.99,0.01],[5,14.95,0.05]]");

If you are working with older browsers that lack the built-in JSON object, consider downloading Crockford's json2.js, which provides a similar API for handling JSON data whenever it is not already available.

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

How to properly escape a double quote in the `eval` function

I am facing an issue with a link button in a gridview as shown below <asp:LinkButton ID="lbtnEdit" runat="server" OnClientClick='<%# String.Format("Edit(\"{0}\", \"{1}\");return false;",Eval("Comment").ToString(),Eval("Statu ...

How come the values (quantity, cost, total) are being stored as zero upon submission, despite successfully transferring the values from the dropdown list to the input using JavaScript?

1. Explanation I am transferring the quantity and price of a product from a dropdown list to input fields. Then I calculate the sum of quantity * price in the third input field. If the quantity or price changes, the sum is automatically updated and disp ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

Creating two separate canvas elements with their own unique JavaScript code can be achieved by first defining each

In my current project, I am utilizing the power of Three.js to craft a 3D cube that can both translate and rotate within a 3D space by harnessing data from accelerometer and gyroscope sensors. Initially, I managed to create one canvas that accurately disp ...

Using GSON libraries to parse a JSON string retrieved from a URL through a RESTful webservice on an Android device

Before proceeding further, I would like to mention that I utilized downloadable GSON libraries in this specific program. For more information on these libraries, please visit the following link: Over the course of my endeavors to parse JSON data, I encoun ...

Close Modal When Clicked Outside of It - CSS & JS

Presently, I am in the process of creating my own modal for the system. When you click on a package name, the modal pops up and is displayed. I have implemented some JQuery code that should remove the modal when clicking on the background. However, it also ...

Ways to extract a value from an object with no properties using jQuery

In order to perform statistical calculations like Averages (Mean, Median, Mode) on data extracted from Datatables, I need the automatic calculation to remain accurate even when the table is filtered. While I have managed to obtain the desired values, extra ...

node.js issue with chalk package

**When I want to use the chalk package in node.js, I encounter the following issue:** index.js const chalk = require('chalk'); console.log(chalk.bgRed.inverse("hello world")); console.log(chalk.blue.inverse('Hello') + &ap ...

presenting JSON data in a table format accurately

I recently created an ajax function that sends a get request to an API and retrieves JSON data, which I then display in a table. Here is what I have attempted: <script> function getInfo() { $.ajax({ type: "GET", url: "http: ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

Use href id to navigate back to the top of the page by

I am trying to implement a function that scrolls the div to the top position. However, I am encountering an issue with retrieving the href value. When I use 'a' in console.log(a);, it returns undefined. function myFunction() { var a=$ ...

Pass on the property ids (Array) from one Test Case to another in SoapUI using Groovy

Is there a way to transfer IDs from one API to another within SOAPUI? I have an API that provides a list of ids, names, and data (TestCase name GET-APIs_OrderdByID_ASC) and I need to transfer these IDs to other TestCases in the same TestSuite or different ...

Generating a JSON array from a C# collection can be achieved by utilizing the System.Web.Script.Serialization

Can someone help me with this code snippet? var httpWebRequestAuthentication = (HttpWebRequest)WebRequest.Create("http://api"); httpWebRequestAuthentication.ContentType = "application/json"; httpWebRequestAuthentication.Accept ...

User has logged out, triggering the browser tab to close automatically

Is it possible to automatically log out the user when all browser tabs are closed? How can I obtain a unique ID for each browser tab in order to store it in local storage upon opening and remove it upon closing? Here is what I have attempted: I am utiliz ...

Troubleshooting KuCoin API: Dealing with Invalid KC-API-SIGN Error and FAQs on Creating the Correct Signature

I want to retrieve open orders for my account using the following code snippet: import { KEY, PASSWORD, SECRET } from "./secrets.js"; import CryptoJS from "crypto-js"; const baseUrl = 'https://api.kucoin.com' const endPointOr ...

What is the best method for choosing the parent elements?

I am attempting to create a sidebar that saves the last clicked link in local storage and still displays the collapsed links after the page is reloaded. $(".clickedLink").parent().parent().css('background-color', 'green'); Ca ...

Retrieve the $scope object within an isolated directive

Is there a way to modify a $scope variable from within an isolated directive? I've experimented with the '@, =, &' syntax in the directive scope but haven't been successful. Here's a simplified version of my code: JS app.co ...

optimal application of css with jquery

I have a question about using jQuery to set the padding of a class or id. I am able to successfully change the height of an element with this code: $('.menu').css({ height: '90px' }); But now, I need to apply a specific CSS rule in jQ ...

Obtain the non-dynamic route parameters as query parameters in Next.js

I need help figuring out how to extract specific query parameters from a URL in my component. I want to exclude dynamic route parameters, such as {modelId}. For example, if the URL is /model/123456?page=2&sort=column&column=value, I only want to re ...