Home > Mobile >  Flutter/Dart how to check key in multidimensional json exists or not
Flutter/Dart how to check key in multidimensional json exists or not

Time:02-11

I get response json like this from server :

{ 
  gender": {
    "label": "Wanita"
  }
}

but sometime i get response like this :

{ 
  gender": []
}

how to handle if key "label" in gender not exist?

CodePudding user response:

To check if a map contains a key you can use containsKey. Small example:

final map = {
    'gender': {
      'label': 'Wanita',
    },
  };

print(map.containsKey('gender')); // true
print(map['gender']?.containsKey('label')); // true
print(map['gender']?.containsKey('age')); // false

But somehow your server responses either a Map or a List. So for your case you have to check the type of the response with the is keyword.

final map = {
    'gender': {
      'label': 'Wanita',
    },
  };
print(map['gender'] is Map) // true
print(map['gender'] is List) // false

final map2 = {
    'gender': [],
  };
print(map2['gender'] is Map) // false
print(map2['gender'] is List) // true

CodePudding user response:

After parsing the server response into a Dart map by using something like jsonDecode provided by the native dart:convert package, you should be able to check the type of the value with the particular key. As you stated, the response will be a list instead of a map if there is no label key, therefore this should do the trick.

import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'] is List) {
    print('no label');
}

In case it returns an empty object, you would check if the key exists in the corresponding object like

import 'dart:convert';

Map response = jsonDecode(rawResponse);

if(response['gender'].containsKey('label')) {
    print('has label');
}
  • Related