user3038167
user3038167

Reputation: 15

Create object from text

I have javascript text:

var textObject = '

        {
            news: [
                                                      { 
                "title":"aaa",
                "desc":"bbb"
                },                                      { 
                "title":"ccc",
                "desc":"ddd"
                }          ]
        }; 

'

but this is in text in my variable. If i have this in code html this working ok, but i get this data with ajax from PHP script.

So how can i convert/parse this text to object? If i have JSON then i can use JSON.parse(textObject); but this isn't json.

Upvotes: 0

Views: 305

Answers (2)

Blue Skies
Blue Skies

Reputation: 2975

Using eval can result in serious performance degradation.

Since you can't do JSON, then use the Function constructor instead so that the evaling takes place in the global scope, and the browsers can still optimize the local code.

var result = new Function("return " + textObject.trim())();

You'll need to shim .trim() to support IE8. If the string is as you show with line breaks at the beginning, then the .trim() will be necessary.

Upvotes: 1

kkemple
kkemple

Reputation: 992

Eval is frowned upon for a lot of reasons, however it also has its benefits if used properly, it is used for a lot of template engines and a few other things but it will convert a string to an object.

var someString = '{obj: "with content"}';
eval( someString );

Here is a working example with your string: http://jsfiddle.net/kkemple/CwzRh/

Upvotes: 1

Related Questions