I have the following switch/case statement which returns data from the json object below. In reality this will be very long!
Switch statement
switch(val){
case 'chicken':
return json['meat']['main'][val];
break;
case 'beef':
return json['meat']['main'][val];
break
case 'lamb':
return json['meat']['main'][val];
break;
case 'pork':
return json['meat']['main'][val];
break;
default:
return '';
}
json object
json={
"meat": {
"main": {
"chicken": "Roast chicken and vegetables",
"beef": "Beef and Yorkshire pudding",
"lamb": "Lamb shank with red currant gravy",
"pork": "Pork and apple sauce",
}
}
}
As you can see, the switch statement is very repetitive as every case statement returns the same expression (although the value it returns will be different as it is accessing a variable key [val] in the object).
In reality my json file is huge, so I want to avoid manually typing out a case statement for each meat (chicken, beef, lamb, pork). Instead I would like to iterate through my json object getting the value at json['meat']['main'][i] (where i is a counter) to create each case. Is this possible? And if not, is there an alternative approach?
Many thanks!
Katie
return json.meat.main[val]should workswitchstatement doesn't make any sense. If you usejson['meat']['main'][val], you are directly accessing correct value.