readJsonOr static method

List<Map<String, dynamic>>? readJsonOr(
  1. String json
)

Parses a JSON string into a Map object.

If the input string contains a JSON object, it returns that object as a single map in a list.

If the input string contains a JSON array with at least one object, it returns all of the objects as maps in a list.

Otherwise, it returns null.

May throw a FormatException if the input string is not valid JSON.

Implementation

static List<Map<String, dynamic>>? readJsonOr(String json) {
  if (json.isEmpty) return null;

  dynamic jsonObj = jsonDecode(json);

  if (jsonObj is Map<String, dynamic>) {
    return [jsonObj];
  } else if (jsonObj is List<dynamic>) {
    List<Map<String, dynamic>> toReturn = [];

    for (dynamic object in jsonObj) {
      if (object is Map<String, dynamic>) {
        toReturn.add(object);
      }
    }

    if (toReturn.isNotEmpty) return toReturn;
  }

  return null;
}