Split a string containing integer and decimal values into an array

I encountered an issue when converting a string to an array:

var data = "[[1, 2, 3,], [3, 2, 1]]";
var array = JSON.parse(data.replace(/,\s*]/g, ']'));

This problem arises when handling floating point numbers in the input:

var data = "[[2.,23.,1.5904], [4.,23,1.6208]]";

Upon attempting this code in the browser console:

var ar = JSON.parse(data.replace(/,\s*]/g, ']'));

An error occurs with the message:

SyntaxError: JSON.parse: unterminated fractional number at line 1 column 5 of the JSON data

The root of this issue seems to lie within the regexp used by JSON.parse(), which is challenging for me as I am not well-versed in regex.

I've experimented with tools like for better understanding, but alas, the problem persists.

This question serves as an extension to a previous one that I had resolved:

Convert string of array, with array of array(s)

At that time, I overlooked the need to accommodate floating points in addition to other data types.

Answer №1

An issue arises when dealing with JSON that requires a decimal number to have a digit following the dot.

To rectify this, the JSON should be structured as follows:

let data = "[[2.0,23.0,1.5904], [4.0,23,1.6208]]";

To resolve this issue, you can either ensure the output includes full floating-point numbers (where feasible) or manipulate the string by adding zeroes after any dots using the following code snippet:

data.replace(/\.,/g, ".0,").replace(/\.]/g, ".0]");

It's crucial to note that adjustments are required not only for dots near commas but also those adjacent to closing square brackets ].

Answer №2

To quickly resolve this issue, you can implement the following:

data.replace(/\.,/g, ".0,)

This command will substitute every occurrence of ., with .0, within the text.

Alternatively, you have the option to use:

data.replace(/\.,/g, ",")

By utilizing this code snippet, you will eliminate any dots preceding the commas in your data.

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 JSON File data and showcasing it with Python

There is a JSON data source at 'https://api.exchangerate.host/symbols' that contains information in the format 'symbols': {'AED': {'code': 'AED', 'description': 'United Arab Emirates Dirham& ...

Display Rails view using JavaScript when clicked

I have a task to create a view where users can click on different buttons and see different content displayed based on the button they choose. I attempted to achieve this using JavaScript, but unfortunately, I couldn't get it to work as intended. Init ...

Develop a custom JavaScript code block in Selenium WebDriver using Java

Recently, I came across a JavaScript code snippet that I executed in the Chrome console to calculate the sum of values in a specific column of a web table: var iRow = document.getElementById("DataTable").rows.length var sum = 0 var column = 5 for (i=1; i& ...

The array of objects has vanished into thin air

I am receiving a JSON string from my server through a PHP file, which contains 25 meals. The PHP script is initiated by a JavaScript function. My goal is to convert the JSON into an array of objects. The response stream displays the correct values and eac ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

Tips for expanding the HTTP header size within Next.js

Can someone provide assistance for increasing the HTTP header size in my Next.js app? The current size is set at 16384 and I am unable to execute the necessary command node --max-HTTP-header-size=24576 server.js. Looking for help from someone with more e ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

Preventing Jquery Append from Adding Previous Elements

I am struggling to figure out how to display the star rating for each hotel individually. I have 5 hotels, each with a different star rating. Here is my Javascript code: function GetStarHotel() { var parent = $(' p.star '), imagePat ...

An error occurred when attempting to hide or show a jQuery loading animation

Here is the HTML code I am using: <div id="success_message" style="display:none"> <p>Good job!</p> </div> <div id="my-form"> <form> <input>....... (lots of inputs) <input id="my-btn" ...

Apigee Usergrid: Absence of bulk delete feature

Currently, I am utilizing usergrid for storage in a customer project. The data is divided into two collections: carShowrooms and cars. Thus far, everything has been running smoothly. However, there arises a situation where I need to refresh the masterdata ...

Ways to access a global JavaScript object in a separate .js file

How can I access an object that was initialized in my HTML document? This is what my HTML document looks like: ... <script type="text/javascript" id="controller">var controller = false;</script> ... <body onload="controller = ne ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

Exploring the function.caller in Node.js

Currently, I have a task that relies on function.caller to verify the authorization of a caller. After reviewing this webpage, it seems that caller is compatible with all major browsers and my unit tests are successful: https://developer.mozilla.org/en-U ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Show only the portion of the image where the cursor is currently hovering

Information in advance: You can check out the current code or view the live demo (hover image functionality not included) at . The concept: I would like to have it so that when I hover my cursor (displayed as a black circle) over the image, only the s ...

How can I fetch data from another table by querying array values in Postgresql?

I have recently started working with a database that includes an array field (Phones) containing IDs from another table. I am new to this feature and I am wondering how I can retrieve all the records from the Public_Phone table that are associated with the ...

Using JSON data in a Java servlet can be done by first creating a JSON

I am working with knockout js and need to send json data to my servlet. I am having trouble extracting the value of a key from the json data. Here is an example of my json data: {"data":[{"BranchId":"xzc","Name":"zxc","Description":"zxc","Template":"Templ ...

Adding a marker to Google Maps in React that displays the user's current location

I successfully integrated Google Maps into my website and now I want to add a marker for the user's location. The first file is Map.js, and the second one is MapContainer.js. In MapContainer.js, I have all the necessary data for map rendering, includi ...