Transform a JSON string into an array of lists

Here's a string I'm working with:

var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";

I want to convert this string into an array of lists. For example,

alert(my_str[1])

would output 1,15.

I've attempted the following approach:

var myarray = JSON.parse(my_str);

However, it results in the error "unexpected token ( in JSON at position 1."

Answer №1

After multiple attempts, I finally came up with a solution

let newArray = JSON.parse(my_json); 

However, this resulted in an error message stating "unexpected token ( in JSON at position 1"

Determined to find a fix, I decided to restructure my string:

let my_json="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";

To my relief, this adjustment worked perfectly!

Answer №2

The issue lies in the unconventional syntax used to separate inner objects. It would be more suitable to utilize "[" and "]" instead of "(" and ")". Nevertheless, you can easily rectify this with JavaScript by converting your structure into an array of arrays of strings. This may sound unusual, but it enables you to create a valid JSON object and take advantage of built-in JS methods.

var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))

You can now manipulate the my_array object and access pairs of numbers using array indexes

my_array[1] ---> 1,15

Answer №3

To properly format the array, you need to make sure to replace all instances of ( with '( and ) with ')', then use the eval function:

eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]

Answer №4

This solution may seem simplistic, but it proves effective without the use of JSON.parse or eval:

var data = my_string.replace('[(', '').replace(')]', '').split('),(');

//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]

Answer №5

let words = message.split("),(")
words[0] = words[0].substring(2);
words[words.length-1] = words[words.length-1].slice(0,-2)

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

Displaying JSON data within a div section using Ajax and jQuery is not possible

I have generated a JSON in a specific format from an external PHP file: [ { "title": "Welcome!", "description": "The world has changed dramatically..", "image": "img/strawberry-wallpaper.jpg" } ] I am trying to use this data to populate a par ...

Obtain the unique identifier for every row in a table using jQuery

Apologies for not including any code, but I am seeking guidance on how to use an each() statement to display the ID of each TR element. $( document ).ready(function() { /* Will display each TR's ID from #theTable */ }); <script src="https:// ...

Creating a high-performing JavaScript script using AJAX: Tips and Tricks

When it comes to structuring my JavaScript scripts, I often find myself following a similar pattern when dealing with AJAX or server responses. However, I don't believe this is the most efficient method. Is there a better approach for handling these t ...

Steps to activate the back button after submitting a form

Having a complex form that leads to a preview page raising concerns: Upon continuing, the preview page is displayed in this manner. Struggling to incorporate the "go back and edit ad" button using JavaScript history -1. This doesn't work as the form ...

Transforming text input into an array of text in PostgreSQL

I have a table named t1 id | names ----|------------------------- 1 | {jully , alex , sarah} 2 | {bety , cate , jenifer} 3 | {adam , pit , joee} 4 | {piter , mat , andy} My goal is to retrieve rows that contain at least one name starting wi ...

Issue with Tooltip Position when Scrolling Sidebar is causing display problems

My goal is to create a Sidebar with Tooltip attached to its <li> elements similar to this example: Screenshot - Good Tooltip However, I am facing an issue where the position of the Tooltip breaks when scrolling to the bottom of the sidebar, causing ...

Leveraging the useRef hook to adjust the CSS styling of a React component

Currently, I am working on changing the style of a react component by utilizing the useRef hook. So far, I have implemented the useRef hook to reference the specific component whose style I want to modify when clicking on two buttons. Despite my efforts, I ...

Objective-C's implementation of arrays in the style of C, Java, and other programming

Although Apple prefers using NS objects instead of primitive types, I require the functionality of an array for direct access to items at specific indices. It's challenging to find tutorials or resources on how to use basic primitive arrays due to thi ...

Using tweepy in Python to fetch Twitter Trends, and then parsing the JSON data

Hey there, just wanted to mention that this is my first time posting here! I'm currently experimenting with Python in order to retrieve Twitter Trends, specifically using Python 2.7 and Tweepy. Here's a code snippet that has been working for me ...

Integrate hash filtering for external links using a custom solution similar to Isotope

Illustration: When a user clicks on a specific link within a webpage, they will be redirected to tailored content in a designated section. I attempted to create a custom isotope using basic hide and show classes, but I am facing difficulty connecting ...

How can I dynamically load a 3D model (in JSON format) at the current location of the mouse using Three.JS?

I'm currently working on a feature that involves loading a 3D model based on the mouse's position. Utilizing jQuery drag and drop functionality for this purpose has helped me load the model onto the canvas successfully, but I'm facing issues ...

Utilizing Angular's ng-repeat with varying directives for each iteration

I am trying to utilize ng-repeat within Angular to iterate through multiple <li> elements with a directive embedded. My goal is to have the first two items in the ng-repeat display differently in terms of styling and content compared to the remaining ...

Implementing a function as state in React Router v6: A step-by-step guide

I am looking for a way to share state between two routes by clicking on the link of one route (NewUser). The state and logic that need to be shared are both located in the Users route. I want to pass the logic for modifying the state to the NewUsers route. ...

How can I resize several images to fit seamlessly within a div container?

Looking for a smart method to resize multiple images to fit neatly inside a fixed-size div? I've considered using JavaScript to calculate the div's width, dividing it by the number of images, and resizing them equally while maintaining their asp ...

Repeated action of rows with the same value

I am currently rebuilding this module within my application using AntDesign. However, I am looking to add a duplicate function that captures the values entered as well. https://i.sstatic.net/IvdqW.png Here is my code snippet, but it seems to not be funct ...

bootstrap-grid (wenzhixin) --> Loading Data through Ajax

I am looking to integrate the bootstrap-table library from wenzhixin () into my project, but I am struggling with getting the script up and running. My goal is to populate the table with data using ajax calls. Below is a sample code snippet provided by t ...

Utilize the event bus by calling `this.$root.$emit` command

I recently implemented a basic Event bus in my application to dynamically change styles on a page, and it's functioning correctly. The event bus is triggered using the $emit and $on methods as shown below: EventBus.$on and EventBus.$emit('call ...

Guide to verifying current data using the jQuery validation library combined with CodeIgniter 4 in the presence of automatic CSRF protection

I am currently working on validating a form using the jQuery validation plugin and CodeIgniter 4. I have enabled CSRF protection that auto generates for each request. Initially, I can successfully validate the form on the first request. However, on subsequ ...

Is there a way to quickly send information to this page using $_POST without the need to physically submit a form to it?

I currently have this code snippet: $.ajax({ type:'GET', url: 'save_desc.php?scrapbook_name=<?php print(addslashes($scrapbook_name)); ?>', success: function(data){ $("#" + id + "below").html(data); } }); How ...

What is the process of converting TypeScript to JavaScript in Angular 2?

Currently diving into the world of Angular 2 with TypeScript, finding it incredibly intriguing yet also a bit perplexing. The challenge lies in grasping how the code we write in TypeScript translates to ECMAScript when executed. I've come across ment ...