Devsined Devsined - 1 year ago 322
Javascript Question

Issue with JSON.stringify adding a extra \ and "" to my Json object

Hi I am creating using Javascript an array of object with a key and a value using the following code.

ValuesArray.push({ key: $(this).attr('someattribute'), value: $(this).val() });

As a result I have am array of object like this:

key:29; value: 'Country'
Key:12; value: '4,3,5'

when I am trying to stringify it and send that JSON in a post I am having a wrong formatted JSON with \ and " in places that I dont want so when I try to desirales that JSON as a JObject on codebehind with C# I am having trouble. How can I create a clean JSON using the stringify

var jObject = JSON.stringify(ValuesArray);

My JSON now which is wrong is:

"JObject": "[{\"key\":\"29\",\"value\":\"Country\"}, {\"key\":\"30\",\"value\":\"4,3,5\"}]"

I would like to have a JSON object like this

"JObject": [{"key":"29","value":"Country"},{"key":"30","value":"4,3,5"}]

without the quotes around the
and the character

Any good idea to solve it.

Thank you

More detail this how I am sending the JSON to my API
this is how I am sending the JSON to my Web API:

function PostAPIRequest(address) {

var jObject = JSON.stringify(ValuesArray);

var responseJson = null;
url: address,
type: 'POST',
dataType: 'json',
data: { JObject: jObject },
success: function (data) {
responseJson = data
error: function (xhr, ajaxOptions, thrownError) {
//TODO redirect to the error page and send error email there.

and this how I am receiving it in my API controller

// POST api/datavalues/5

public string Post(int id, JObject value)
var temp = value;


Answer Source

It looks like you are placing a string as the value in your map. You should do something like:

var objMap = {"JObject" : ValuesArray}; var json = JSON.stringify(objMap)

What's happening is you are double json encoding your values array - note that your "invalid" JSON value is actually a JSON string rather than the array that you want.

EDIT It looks like you are sticking in JSON strings of maps into an Array and then stringifying that. Here's a jsfiddle that should help you get what you are looking for -

In your post request, try this

var jObject = {"JObject" : ValuesArray};
$.ajax({   url: address,
           type: 'POST',
           dataType: 'json',
           data: jObject,
           success: function (data)  { .. }});

Note the change in the data attribute. That is a value that is automatically JSONified for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download