6

In python there exists ast.literal_eval(x) where if x is "['a','b','c']" then it will return the list ['a','b','c']. Does something similar exist in Javascript / jQuery where I can take the array that is stored in the table cell as [x,y,z] and turn that into a literal JavaScript array?

I'd prefer to avoid any complex solutions that might be error prone since it's possible that involve splitting on the comma or escaping characters.

Edit: I should have given some better examples:

['la maison', "l'animal"] is an example of one that hits an error because doing a replace of a single or double quote can cause an issue since there's no guarantee on which one it'll be.

10
  • the question is not clear. Please clearly mention what will be the input & what is the expected out Commented Feb 8, 2018 at 2:55
  • JSON.parse() is probably what you want. Commented Feb 8, 2018 at 2:56
  • yeah, JSON.parse won't work where "string literals" use ' instead of " .... eval should work though - but understand how evil eval can be Commented Feb 8, 2018 at 2:58
  • @cale_b It won't accept the string he posted, but that's a Python literal, not JSON. Commented Feb 8, 2018 at 2:58
  • @JaromandaX He asked for something "similar", I didn't think he meant it had to accept Python literals. JSON is the analogous thing for Javascript. Commented Feb 8, 2018 at 2:59

2 Answers 2

9

One could leverage String.prototype.replace() and JSON.parse().

See below for a rough example.

// String.prototype.replace() + JSON.parse() Strategy.
const input = "['a','b','c']" // Input.
const array = JSON.parse(input.replace(/'/g, '"')) // Array.
console.log(array) // Proof.

Although, given your update/more complex use case, eval() might be more appropriate.

// eval() Strategy.
const input = `['la maison', "l'animal"]` // Input.
const dangerousarray = eval(input) // Array.
const safearray = eval(`new Array(${input.replace(/^\[|\]$/g, '')})`) 
console.log(dangerousarray) // Proof.
console.log(safearray) // Proof.

However, the MDN docs discourage use of eval() due to security/speed flaws.

As a result, one may opt for an approach similar to the following:

// Heavy Replacement Strategy.
const input = `['la maison', 'l\'animal']` // Input.
const array = input
  .replace(/^\[|\]$/g, '') // Remove leading and ending square brackets ([]).
  .split(',') // Split by comma.
  .map((phrase) => // Iterate over each phrase.
    phrase.trim() // Remove leading and ending whitespace.
    .replace(/"/g, '') // Remove all double quotes (").
    .replace(/^\'|\'$/g, '') // Remove leading and ending single quotes (').
  )
console.log(array) // Proof.

Sign up to request clarification or add additional context in comments.

Comments

5

In JavaScript you can use eval() Function like the sample bellows :

// define the string to evaluate
var str_to_evaluate = 'new Array("Saab", "Volvo", "BMW")';

// retreive the result in a array
var cars = eval(str_to_evaluate);

// print the array
console.log(cars);

3 Comments

var str_to_evaluate = '$.ajax(...)
simple, don't use jQuery :p
It turns out that slicing the hard brackets off, and appending the new Array ( and ) to the ends made this the best choice considering that there could be both single or double quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.