Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform data when parsing a JSON string using Dart

Tags:

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])
like image 602
Shailen Tuli Avatar asked Jul 08 '13 16:07

Shailen Tuli


1 Answers

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
}
like image 81
Shailen Tuli Avatar answered Nov 05 '22 08:11

Shailen Tuli