1

Hi I am using an asp.net MVC controller to query a third party REST API.

I am getting a response but it has newline characters in the response.

{\n \"from\": 1,\n \"to\": 10,\n \"total\": 500570,\n \"currentPage\": 1,\n....

I am returning this to a view and the view is not able to read it because of \n.

I am using the following code to make the call and get the result

   public JsonResult Items(string search)
    {

        var client = new WebClient();
        string url = "http://xxxxxxxxxxxxxxx/v1/products?apiKey=xxxxxxxxxx&format=json";


        JsonResult json = Json(client.DownloadString(url), "text/x-json",Encoding.UTF8, JsonRequestBehavior.AllowGet );


        return json;
    } 

In the view side following script

<script type="text/javascript">

    $(function () {
        $('#searchlink').click(function () {
            $.getJSON("Item/Items", $("#search").val(), getitems);

        });
    });

    function getitems(responses) {
        alert(responses);

        $.each(responses, function (index, response) {
              // do stuff
        });
    }

</script>

What am I doing wrong here?

2
  • Have you verified that the API's response isn't including newlines? Commented Feb 8, 2011 at 1:49
  • Yes i have verified, API's response is including and that's why i am amazed that, is that something i am doing wrong because i am trying this first time. Commented Feb 8, 2011 at 7:17

1 Answer 1

2

If you want to remove all the \n Characters you can remove the NewLines in the Controller before send it to view:

string result=client.DownloadString(url);
result=result.Replace("\r", "").Replace("\n", "\n");

If you want to keep the NewLine Characters you must Escape them in Javascript before you parse Json:

$.get("Item/Items", $("#search").val(), getitems(data) {
    //Escape \r,\n
    data=data.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
    //and parse Json
    responses=jQuery.parseJSON(data);
    alert(responses);

    $.each(responses, function (index, response) {
          // do stuff
    });
});
Sign up to request clarification or add additional context in comments.

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.