JavaScript - Deserializing an array of strings

I am facing an issue with converting a string to an array. The original string looks like this:

a= "['url1','url2','url3']"

When trying to convert it to an array, it should look like this:

arr = ["url1","url2","url3"]

However, using JSON.parse does not seem to be working and is throwing the following error:

SyntaxError: Unexpected token ' in JSON at position 1

Your help on this matter would be greatly appreciated.

Answer №1

To convert single quotes to double quotes, one simple method is to use escaped quotes as shown below:

let validJSON = a.replace(/'/g, "\"")

JSON.parse(validJSON)

Answer №2

For JSON.parse to function in this scenario, your string must be enclosed within single quotes. It is important to note that the standard representation for strings in JSON involves using double quotes.


JSON.parse('["url1","url2","url3"]')

Answer №3

Check out this code snippet:

let a = "['link1','link2','link3']";
let urls = a.split(',');
let arr = urls.map(url => url.replace(/'|\[|\]/g, ''));

console.log(arr) // ["link1", "link2", "link3"]

https://jsfiddle.net/abc123xyz/

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

Make the div disappear upon clicking the back button in the browser

When a user selects a thumbnail, it triggers the opening of a div that expands to cover the entire screen. Simultaneously, both the title and URL of the document are modified. $('.view-overlay').show(); $('html,body').css("overflow","h ...

Supplying a lengthy JSON string as an input for a GRAPHQL mutation

Upon receiving a large stringified JSON from the client, my intention is to utilize this JSON data to create items in my database. I have a mutation that accepts this JSON as a string input. Within the mutation, I parse the JSON and then leverage it to pop ...

Implement a Vue binding that applies an active class on click, replacing the previous one

I have a loop that dynamically adds div sections to the page. I want the first one to be selected on page load, and then when another one is clicked, it should become active while the previous one loses its active status. I attempted the code below but it ...

Is there a way to extract just the JSON data from res?

While creating a search functionality to display a list of users, I encountered an error when attempting to load additional pages to show more users: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data var result = JSON.pars ...

What is the best way to utilize an accordion feature to display collections of documents?

My request: 1. Retrieve data from a MongoDB collection and display it in an accordion format on a webpage. 2. Ensure that the active ID of the selected HTML accordion tag matches the document ID from the collection. 3. Implement a dropdown transition ...

Include "clickable" commas among various <span> elements

Struggling to insert commas between a series of items? Well, fear not! If you're wondering how, it can be achieved with a simple line of code: .comma:not(:last-of-type)::after{ content: ", "; } <span class="comma">A</span> <s ...

AngularJS - activating $watch/$observe event handlers

I am looking for a way to trigger all $watch/$observe listeners, even if the watched/observed value has not changed. This would allow me to implement a "testing only" feature that refreshes the current page/view without requiring user interaction. I have a ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

How can I modify the style of table rows with CSS?

Is there a way to change the color/background of a selected row just like it does on hover, and also have the option to deselect the row? To see how it looks on hovering, check out: http://jsfiddle.net/q7ApN/ If you want to make a Change: #gradient-styl ...

Importing usernames and passwords from a .txt file with Javascript

I'm in the process of creating a website that includes a login feature. The usernames and passwords are currently stored within the website files as .txt documents. I am aware that this method is not secure, but for the purpose of this project, I want ...

Encountered a DataTables warning: an Ajax error has occurred with table id=products. To gain a deeper understanding of this issue, kindly refer to http://datatables.net/

Whenever I run the script, an error message pops up saying "127.0.0.1:60809 DataTables warning: table id=products - Ajax error. If you need more information about this error, please visit http://datatables.net/tn/7". Here is the image of the error. The i ...

An object in typescript has the potential to be undefined

Just starting out with Typescript and hitting a snag. Can't seem to resolve this error and struggling to find the right solution useAudio.tsx import { useEffect, useRef } from 'react'; type Options = { volume: number; playbackRate: num ...

displaying error message after calling API on Node.js express server

I'm currently working on error handling on the front end, using responses from my Express server. The process involves sending data from the front end to the Express server via a POST request. The endpoint (referenced as /endpoint below) then communic ...

Steps to incorporate iframe into a webpage with 100% height and enable page scrollbars

Looking to seamlessly integrate an iframe into a webpage? Here are the requirements: The iframe height must adjust to fit its content, occupying 100% of available space. Hide scrollbars within the iframe, allowing the page's scrollbars to adjust acc ...

Fatal Error Alert: The Comprehensive Absolute Values Chart

I've been struggling with this homework assignment for quite some time now. Despite my efforts, I can't seem to pinpoint the root of the issue. My main concern is why am I consistently encountering segmentation fault errors whenever I run this p ...

Using Ajax (Jquery) to send data to a PHP script

Currently, I am working on an application where users can click a checkmark to complete a task. When this action is taken, a popup window appears (created using bootstrap), prompting the user to enter their hours worked on the task. After entering the hour ...

Exploring the method of displaying a JSON 2D array through the utilization of getJSON

Is there a way to read 2D JSON data? An example of a JSON file is given below: [ { "name":"Menu1", "permission":"1", "link":"http://naver.com" }, { "name":"Menu2", "permission":"2", "link":"http://daum.net", ...

Adding an array to a table in a database is a necessary

As a newcomer in the world of PHP, I am currently honing my skills in working with databases and arrays. Within my database, I have two tables set up. Successfully retrieving data from one table and storing it in an array, my next goal is to transfer this ...

Ruby - adding elements to an array depending on a specified percentage

I have a class named TestSubject that stores two properties: name and percent. I am trying to add the name to an array based on the percentage value. For example, arr.push(TestSubject.name) with a chance of TestSubject's percentage being puts TestSub ...

The IllegalStateException thrown was due to anticipating a BEGIN_ARRAY, but instead encountered a BEGIN_OBJECT

I need assistance in fixing this error. Can you help me identify the problem? private final String TAG = "MulaiUjian"; private RecyclerView recyclerView; private LinearLayoutManager layoutManager; private RecycleViewAdapter adapter; @Override protected ...