Naren Naren - 21 days ago 8
Javascript Question

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)

[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]


I am building request below in javascript.

var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'

var atrUserLegendsInputs

for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}

atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);

var legendIds = '[' + atrUserLegendsInputs + ']';

var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);


getting error message:

{["The input was not valid."]}


I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue

Answer

Try this code

var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';

//* create empty array  for legends
var atrUserLegendsInputs = [];

for (i = 0; i < list.get_items().get_count() ; i++) {
    //* put some values into legends' array
    atrUserLegendsInputs.push({ 
        atrSpaUserId: administratorId,
        atrSpaClassLegendId:     list.getItem(i).get_value(),
        atrSpaCityDistrictId: districtId
    });
}

var atrDistrictLegend = {
    districtID: cityDistrictId,
    legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);
Comments