Shailen Tuli
Shailen Tuli

Reputation: 14201

Transform data when parsing a JSON string using Dart

I'm using the parse() function provided in dart:json. Is there a way to transform the parsed data using parse()? I'm thinking of something similar to the reviver argument when parsing JSON using JavaScript:

JSON.parse(text[, reviver])

Upvotes: 10

Views: 3545

Answers (1)

Shailen Tuli
Shailen Tuli

Reputation: 14201

The parse() function in dart:json takes a callback as an arg that you can use to transform the parsed data. For example, you may prefer to express a date field as a DateTime object, and not as a list of numbers representing the year, month and day. Specify a ‘reviver’ function as a second argument to parse.

This function is called once for each object or list property parsed, and the return value of the reviver function is used instead of the parsed value:

import 'dart:json' as json;

void main() {
  var jsonPerson = '{"name" : "joe", "date" : [2013, 10, 3]}';

  var person = json.parse(jsonPerson, (key, value) {
    if (key == "date") {
      return new DateTime(value[0], value[1], value[2]);
    }
    return value;
  });

  person['name'];             // 'joe'
  person['date'] is DateTime; // true
}

Upvotes: 14

Related Questions