user42826
user42826

Reputation: 101

Convert string loaded from text file to an array object in JavaScript

I have the following object

            {   
                    value: 20, 
                    color:"#878BB6"
            },  
            {   
                    value : 40, 
                    color : "#4ACAB4"
            } 

loaded from a text file abc.txt in my local directory in the server.

I want to convert this into an array object. I tried doing

    var string = "{   
                    value: 20, 
                    color:"#878BB6"
            },  
            {   
                    value : 40, 
                    color : "#4ACAB4"
            }"

     var array = JSON.parse("[" + string + "]");
     alert(array);

Nothing happens unfortunately. Help appreciated !

Upvotes: 1

Views: 2150

Answers (1)

Chris Pietschmann
Chris Pietschmann

Reputation: 29905

You can use "eval" to accomplish what you are attempting.

var s = '{value: 20,  color:"#878BB6" },' +
        '{value : 40,  color : "#4ACAB4"}';

var arr = eval('[' + s + ']');

alert(arr[0].value);

Also, in order for JSON.parse to parse it the string needs to be valid JSON. So you'll need to have quotes around the object property names. Like the following:

var s = '{"value": 20, "color":"#878BB6" },' +
        '{"value": 40, "color": "#4ACAB4"}';

var arr2 = JSON.parse('[' + s + ']');
alert(arr2[1].value);

Although it would be better to modify the process for generating the text file to contain valid JSON if you can. Then you could use jQuery or some other method of just loading the JSON from the file directly.

Upvotes: 2

Related Questions