Troy Reyes
Troy Reyes

Reputation: 42

Posting Array in Javascript

First, I want to thank stack overflow before posting this. Here's the scenario. I want to Post Array [["a","b"],["c","d"]] in javascript. And Return data as the same [["a","b"],["c","d"]]. But I got these value - "[[\"a\",\"b\"],[\"c\",\"d\"]]"

Thanks in advance.

var arraylist = [["a","b"],["c","d"]];

$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
    alert(data);
    }            
});

My TestReciever.cshtml code is :

string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var j = Json.Encode(input);
Response.Write(j);

Upvotes: 0

Views: 61

Answers (2)

Nadir Laskar
Nadir Laskar

Reputation: 4150

In your code

string input;
using (var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
// Your are encoding the JSON data to STRING 
   var j = Json.Encode(input);  // Its like doing JSON.stringify in JS
   Response.Write(j);

This line var j = Json.Encode(input); is converting your JSON to an string. what its doing in your code is that as your JSON consist of double quotes in its structure. so, its basically escapes them. like from [["a","b"],["c","d"]] to "[[\"a\",\"b\"],[\"c\",\"d\"]]";

In javascript you need to do JSON.parse(YOUR_RESPONSE) to read the data as a array.

$.ajax({
async: true,
type: "POST",
url: "/TestReciever.cshtml",
data: JSON.stringify(arraylist),
success: function (data) {
       var your_array = JSON.parse(data); //This will parse your string to ARRAY
       /* NOW USE YOUR ARRAY HERE AS A NORMAL ARRAY*/
    }            
});

For more information on JSON.parse

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

If your are confused if array can be a JSON here is an great answer.

Upvotes: 1

jonasfh
jonasfh

Reputation: 4569

It looks like your problem is in the cs-code, not the javascript. The line var j = Json.Encode(input); will json-encode the already json-encoded string coming from your site. If you simply return your input, you should get the correct json back.

Upvotes: 1

Related Questions