0

I'm new with javascript. I want to know if there is a possibility to convert a DOMString (taken by reading a file saved in the Filesystem) and converting it into an Array, since I need it to perform an operation. I'm using e.target.result to read the content of the file, and the result is

{element: "one", value: "one"},
{element: "two", value: "two"},
{...},
{...}

and I need the array saved in this way

var array = [{element: "one", value: "one"},
            {element: "two", value: "two"},
            {...},
            {...}]

any Idea how to do it? Thanks in advance

  • Could you please add how exactly does the input you have, look? – mavrosxristoforos Oct 22 '13 at 18:59
  • Exactly the output of the reading, that should be also the input for the array is `[{element: "one", value: "one"}, {element: "two", value: "two"}, {...}, {...}]` I've tryed to simply assign it to an array variable but it doesn't work – user2908435 Oct 22 '13 at 19:13

2 Answers2

0

you might give the split() function a try.

var prearray = '{element: "one", value: "one"},{element: "two", value: "two"}';
var realarray = prearray.split(",");

http://www.w3schools.com/jsref/jsref_split.asp

fkaefer
  • 16
  • 2
0

You can use eval to do this for you:

var array = eval("["+item+"]");
array[0].element //"one"
array[0].value //"one"
array[1].element //"two"
array[1].value //"two"

Fiddle: http://jsfiddle.net/KyleMuir/NZwAx/

Warning, eval can be extremely dangerous (code injection if from a third party, notoriously hard to debug if anything more complex than this example and also can have performance issues): https://stackoverflow.com/a/198031/2469255 so ensure you trust the source of the data that you are eval'ing

Hope this helps!

Community
  • 1
  • 1
Kyle Muir
  • 3,875
  • 2
  • 22
  • 27
  • It's a great idea. the only problem is that now, when I try to execute it, also adding `"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"` in the manifest file, an error occours: **Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.** – user2908435 Oct 23 '13 at 16:15
  • In that case, writing a custom parser looks to be your best option. – Kyle Muir Oct 23 '13 at 17:47