Last updated:
0 purchases
json events
⚠️ In order to support web, this library does not support very big numbers. Check dart's js compatibility regarding numbers
json_events #
A package for parsing large json files/objects. The package processes the json in a forward-only way and emits events based on the tokens it encounters.
Parsing manually #
From a Stream
Stream<List<int>> s = ...;
await for (JsonEvent je in s
.transform(const Utf8Decoder())
.transform(const JsonEventDecoder())
.flatten()) {
print("Event Type: ${je.type.name} Value: ${je.value}");
}
copied to clipboard
From a String
Stream<String> s = Stream.value(...);
await for (JsonEvent je in s.transform(const JsonEventDecoder()).flatten()) {
print("Event Type: ${je.type.name} Value: ${je.value}");
}
copied to clipboard
Using mixin #
For objects #
class MyClass with JsonObjectTraverser {
late int x;
late List<MyClass> arr;
late List<int> pArr;
late List<List<int>> pNestedArray;
String? text;
@override
Future<void> readJson(String key) async {
switch (key) {
case "x":
x = await this.readPropertyJsonContinue<int>();
case "arr":
arr = await this.readArrayJsonContinue<MyClass>(creator: MyClass.new).toList();
case "pArr":
pArr = await this.readArrayJsonContinue<int>().toList();
case "pNestedArray":
pNestedArray = await this.readNestedArrayJsonContinue<List<int>, int>().toList();
case "text":
text = await this.readPropertyJsonContinue<String?>();
}
}
}
copied to clipboard
Then call appropriate loader
MyClass mc = MyClass();
await mc.loadJson(streamIterator);
copied to clipboard
For arrays that are represented as objects #
import "package:collection/collection.dart";
class MyArrayClass extends DelegatingList<MyClass> with JsonArrayTraverser<MyClass> {
@override
FutureOr<MyClass> Function()? get creator => MyClass.new;
MyArrayClass() : super([]);
}
copied to clipboard
Then call appropriate loader
MyArrayClass mc = MyArrayClass();
await mc.loadJsonFromStream(stream);
copied to clipboard
Disclaimer #
Most of the code for the parsing is from dart-sdk
Inspired from dart-json-stream-parser
Test cases are copied from JSONTestSuite
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.