-2
{scenarios: "[{purchasePrice:11,downPayment:1,term:30,rate:1}]"}

That's my object. I want to turn the value of scenarios into the array its trying to be from the string it is.

Is there a quick tool so I don't have to hack it together from .splits?

Aron Greenspan
  • 115
  • 1
  • 6

1 Answers1

0

Yes, if the string comes from a trusted source, you can use eval, which will evaluate the string as JavaScript code:

var scenarios = eval(theObject.scenarios);

Since eval allows running any arbitrary code, don't use it on strings from untrusted sources. Additionally, it tends to make it difficult or impossible for the JavaScript engine to optimize the code it's in, so isolate your use of it in a function so the impact is kept to a minimum.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Even though it's not valid JSON, it's still probably safer to do `JSON.parse(obj.scenarios);` right? – Jonathan Sep 19 '16 at 17:40
  • @Jonathan: Well, no, because that will just fail with an error. ***If*** it were valid JSON, *then* yes, it would be much better to use `JSON.parse`. – T.J. Crowder Sep 19 '16 at 17:40
  • Ah sorry, I see... – Jonathan Sep 19 '16 at 17:41
  • Unfortunately it is a querystring param. Is there another way to store an array of objects safely in the QS? – Aron Greenspan Sep 19 '16 at 18:53
  • @AronGreenspan Why not use [JSON.stringify](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and [JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – Asons Sep 19 '16 at 23:14
  • @AronGreenspan: As LGSon said: Use JSON. So for instance, your string would be `[{"purchasePrice":11,"downPayment":1,"term":30,"rate":1}]`, which would look like `%5B%7B%22purchasePrice%22%3A11%2C%22downPayment%22%3A1%2C%22term%22%3A30%2C%22rate%22%3A1%7D%5D` when URI-encoded, e.g. `http://example.com/foo?scenarios=%5B%7B%22purchasePrice%22%3A11%2C%22downPayment%22%3A1%2C%22term%22%3A30%2C%22rate%22%3A1%7D%5D`. Then you just `JSON.parse` it. – T.J. Crowder Sep 20 '16 at 06:44