Using js-interop how can I convert javascript Array and Object to native dart Map.
Asked Answered
C

3

6

Is it possible to convert a javascript object or array back to native dart Map and/or List? I'm trying to get a manifest file returned from javascript as Object and want to convert it to a Dart Map object.

Clammy answered 18/12, 2012 at 19:18 Comment(0)
C
2

Many changes in API was done by this year, following code is Alexandre Ardhuin's answer adapted to latest (#30104) Dart Sdk

import "dart:convert";
import "dart:js" as js;

convert( js.JsObject object )
{
  return JSON.decode( js.context['JSON'].callMethod("stringify", [ object ] ) );
}
Corpus answered 12/11, 2013 at 16:14 Comment(0)
H
4

You can convert a javascript JSON to a Dart JSON with :

import 'dart:json';
import 'package:js/js.dart' as js;

convert(js.Proxy jsonProxy) => JSON.parse(js.context.JSON.stringify(jsonProxy));
Harkness answered 18/12, 2012 at 20:30 Comment(0)
C
3

You could use the built in Javascript method JSON.stringify() from the Javascript context.

Future getManifest() {
  var completer = new Completer();

  js.scoped(() {
    var chrome = js.context.chrome; 
    var manifest_proxy = chrome.runtime.getManifest();
    var manifest_string = js.context.JSON.stringify(manifest_proxy);
    var manifest = JSON.parse(manifest_string);
    logger.fine("manifest_string = $manifest_string");
    completer.complete(manifest);
  });

  return completer.future;    
}

Which would print out the following to the console and send the completer a dart Map.

manifest_string = {"app":{"background":{"scripts":["main.js"]}},"manifest_version":2,"minimum_chrome_version":"23","name":"chrome.dart - test","version":"1"} 
Clammy answered 18/12, 2012 at 19:43 Comment(2)
You don't need to use a Future.Harkness
Nice, so being scoped does not require a Future return. In this library I started using Future as a pattern to most of the calls provided by chrome.* apis. If this is the case then I should only need Futures for methods that require callbacks. goo.gl/x2H2KClammy
C
2

Many changes in API was done by this year, following code is Alexandre Ardhuin's answer adapted to latest (#30104) Dart Sdk

import "dart:convert";
import "dart:js" as js;

convert( js.JsObject object )
{
  return JSON.decode( js.context['JSON'].callMethod("stringify", [ object ] ) );
}
Corpus answered 12/11, 2013 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.