0

I have an List error Entity which I used to pass errorId and error message to the UI layer.

   public class ErrorEntity
    {
       public int ErrorId
       {
           get;
           set;
       }

       public string ErrorMessage
       {
           get;
           set;
       }
    }
}

I send the object to the Javascript I am serializing it to JSON.

The Json I am getting after serialization look like

[{"ErrorId":1,"ErrorMessage":"Test has not been prepared for tag EP105"},{"ErrorId":2,"ErrorMessage":"Test has not been prepared for tag EP105"}]

Now I need to parse this Json string to show the error message to the user. Please let me know how can I parse it. Do I need to write a for loop to traverse with in it.

EDIT In my master page I am trying to parse it.

function ShowErrorMsg(jsonObject) {  
  for (i = 0; i < jsonObject.Object.length; i++) { //Object is undefined here.
    alert(jsonObject.Object.ErrorMessage);
  }          
}
1
  • 1
    are you using any ajax based libraries like jquery? Some browsers have native ability to parse json string. Which is(are) your target browser(s) Commented Oct 23, 2011 at 10:55

3 Answers 3

2

Prefer JSON.parse() if it's available:

var jsonArray = JSON.parse(serializedString);
window.alert(jsonArray[0].ErrorMessage);

Fall back to eval() otherwise:

var jsonArray = eval(serializedString);
window.alert(jsonArray[0].ErrorMessage);
Sign up to request clarification or add additional context in comments.

3 Comments

What is the more preferred way of doing it. Would eval be safe?
The preferred way to do it is to use JSON.parse(), which only parses the subset of Javascript used by JSON and is safer than eval().
You should use a library like jQuery which should implement the fallback if your browser does not support JSON.parse().
0

Try Json.NET

1 Comment

I am trying to parse it in my script file.
0

There is support in most browsers for parsing json, I recommend to use jQuery for this - you also can take a look at this

Be aware - Its better to use a library - and not using JS for this (JS is from the devil ;) )

Comments

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.