Vinayaka N Vinayaka N - 2 months ago 7
ASP.NET (C#) Question

How to use switch case in JSON

I am trying to display normal message using JSON switch case. I have written code also code is below

<script type="text/javascript">
var text = '{ "R000092201": "EIN and Name should be same","F229000501":"Your Form is Incomplete, Please add the Credit Vehicle Details (Contact Support for any further queries)","F229002201":"Your Form is Rejected, Please ensure you select either EFW or EFTPS Payment (Contact Support for any further queries)"}';

var obj = JSON.parse(text);
var clients = '<%= clients%>';
alert(clients);
switch (clients) {
case 'R0000-922-01': document.getElementById('lblrejectionmsg').innerHTML = obj.R000092201;

case 'F2290-005-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229000501;

case 'F2290-022-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229002201;
}
</script>


In above code based on backend data i.e <%= clients%> corresponding case should execute, but in my code it is not For example clients value whatever always 3rd case message is displaying. Where I have been going wrong please help me.

Answer

You are missing the break; after each case.

<script type="text/javascript">
    var text = '{ "R000092201": "EIN and Name should be same","F229000501":"Your Form is Incomplete, Please add the Credit Vehicle Details (Contact Support for any further queries)","F229002201":"Your Form is Rejected, Please ensure you select either EFW or EFTPS Payment (Contact Support for any further queries)"}';

var obj = JSON.parse(text);
var clients = '<%= clients%>';
alert(clients);
switch (clients) {
    case 'R0000-922-01': document.getElementById('lblrejectionmsg').innerHTML = obj.R000092201;
    break;
    case 'F2290-005-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229000501;
    break;
    case 'F2290-022-01': document.getElementById('lblrejectionmsg').innerHTML = obj.F229002201;
    break;
}

if you miss the break; always all the case after matching case will execute. so add break; after each case block.

Comments