0

I must convert a string representation of an array of objects returned from AJAX to an array of objects in JavaScript.

ajaxret = "[{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]"

strResult = [{a:'a', b:'b', c: 1},{a:'aa', b:'ab', c: 2},{a:'aaa', b:'bbb', c: 3}]
5
  • 3
    If it's valid JSON (which your string is not), you can use JSON.parse(). How are you creating ajaxret? Why is it returning an invalid JSON string? If you can fix ajaxret, then JSON.parse() will work great :) Commented Mar 21, 2014 at 15:26
  • What's missing to make it a valid JSON string? Commented Mar 21, 2014 at 16:02
  • The keys are not quoted. Both the keys and (string) values need to be quoted in double quotes. How are you creating this JSON? Commented Mar 21, 2014 at 16:03
  • VB.Net is used to create a colModel used to load a jqGrid grid. It is originally converted to a simple js array in the Page_Load event using stringBuilder.AppendFormat. However when the same string is requested using Ajax it needs to be loaded into the page using Javascript. In any case, it sounds like there is no easy way to do it. I'll have to try to quote the keys to see if the original page Append.Format will convert it. Commented Mar 21, 2014 at 16:12
  • Check to see if there's a native JSON function. Don't build the JSON manually. Commented Mar 21, 2014 at 16:18

1 Answer 1

1

When you serialize your objects into strings, you should produce valid JSON, using

var string = JSON.stringify(object);

To parse to an object again, then you can use

var object = JSON.parse(string);

In your case, since you have invalid JSON, the simple way is

var object = eval(string);

Warning!!!

  • eval is evil
  • Use it only if the source is completely trusted
  • A malicious source could execute arbitrary code. So bad!
  • JSON.parse is probably faster
Sign up to request clarification or add additional context in comments.

2 Comments

Eval(ajaxRet) worked. How dangerous is it? ajaxRet is completely controlled by the code that creates it based on existing table data which is filled by user input which is added using OleDbCommand using parameters.
@RobGMiller If ajaxRet contains user input, it should be ok to eval it in that user's machine, but not in others' one. Anyway, better use JSON.

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.