开发者

Switch Statement on Json?

开发者 https://www.devze.com 2023-02-14 23:10 出处:网络
I am wondering how do I make a switch statement in json? {\"Errors\":{\"key1\":\"afkafk\"},\"IsValid\":false,\"SuccessMessage\":\"\"}

I am wondering how do I make a switch statement in json?

{"Errors":{"key1":"afkafk"},"IsValid":false,"SuccessMessage":""}

I trie开发者_开发百科d

switch(response)
{
   case response.Errors.key1:
    alert('test');
   default: 
}

But it seems to ignore my first case.

Edit

// if undefined then go to next if statement - I am not sure if I can do something 
// like !=== null
if (response.Errors.key1)
            {
               // display value of key1 
            }
else if(response.Errors.Key2)
{
   // display value of key2 differently
}

So that is what I am trying to do just with a switch statement.


This would be the correct syntax:

switch(response.Errors.key1)
{
    case 'afkafk':
        alert('test');
        break;
    default:
        alert('default');
}

But I suspect that in your case the following structure would be more adapted:

{ Errors: { key: 'key1', message: 'afkafk' }, IsValid: false, SuccessMessage: '' }

because it would allow you to switch on the key:

switch(response.Errors.key)
{
    case 'key1':
        alert(response.Errors.message);
        break;
    default:
        alert('default');
}


It sounds like you want to switch on the value key1 instead of the name key1.

switch (response.Errors.key1) {
  case 'afkafk':
   ...
}


I'm not entirely sure what you're trying to achieve. Are you trying to switch based on the value of key1? Switch statements need to be able to match the variable you pass to the switch statement with the value of a case statement, so the following would work, although I'm not sure if it's what you're after:

switch (response.Errors.key1) {
  case 'afkafk': //do something
  break;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消