0

Im trying to parse JSON from a file in dart. I've managed to read the file and print it, but when I try to convert it to JSON, it throws and error.

file.dart:

import 'dart:convert' as JSON;
import 'dart:io';

main() {
    final jsonAsString = new File('./text.json').readAsString().then(print); //Successful printing of json
    final json = JSON.decode(jsonAsString);


    print('$json');
}

Error:

Unhandled exception:
NoSuchMethodError: No top-level method 'JSON.decode' declared.
Receiver: top-level
Tried calling: JSON.decode(Instance of '_Future')
#0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:196)
#1      main (file:///Users/ninanjohn/Trials/dartTrials/stubVerifier.dart:7:15)
#2      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:265)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)

What am I missing or doing wrong here?

leoOrion
  • 1,833
  • 2
  • 26
  • 52

1 Answers1

3

Firstly, when importing the dart:convert library you are giving it an alias called JSON. Which means you would have to use it like;

JSON.JSON.decode(jsonString);

I think you want to use show instead of as. See this SO question for more details.

The other issue is this line;

final jsonAsString = new File('./text.json').readAsString().then(print);

You're not actually assigning a String to that variable because because the .then() method is returning a Future.

Either read the file synchronously;

final jsonAsString = new File('./text.json').readAsStringSync();
print(jsonAsString);
final json = JSON.decode(jsonAsString);
print('$json');

or change it to...

new File('./text.json').readAsString().then((String jsonAsString) {
  print(jsonAsString);
  final json = JSON.decode(jsonAsString);
  print('$json');
});
stwupton
  • 2,177
  • 17
  • 18