Dart从不可编辑的大文件中读取JSON对象 [英] Dart read json objects from Uneditable large file
问题描述
我有一个无法编辑的大文件,并且其中还有更多 jsonObject
,例如:
i have a large file which that uneditable and i have more jsonObject
into that, for example:
{"id":"@123456","v":"1"}
这不是 jsonArray
我无法解析和读取它,例如:
this isn't jsonArray
which i can't parse and read it, for example:
String file= new File('file.json').readAsStringSync();
Map<String, dynamic> data = json.decode(file);
您认为我该如何从文件中读取此对象并显示键和值?
you think how can i read this objects from file and show key and values?
推荐答案
尝试以下解决方案。我最终为您的输入格式创建了一个解析器,该解析器将返回Stream中每个解析的JSON对象。
Try the following solution. I ended up making a parser for your input format which are returning each parsed JSON object in a Stream.
如果您的JSON中的任何字符串包含<$,解析器将无法工作。 c $ c> {或}
。如果是这种情况,我可以扩展解析器,以便将其考虑在内,但我不想使其超出必要的高度。
The parser will not work if any strings in your JSON contains {
or }
. If that is the case, I can expand the parser so it takes this into account but I don't want to make it more advanced than necessary.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final ids = await File('large_file.json')
.openRead()
.transform(const Utf8Decoder())
.transform<dynamic>(JsonObjectTransformer())
.map((dynamic json) => json['id'] as String)
.toList();
print(ids); // [@123456, @123456]
}
class JsonObjectTransformer extends StreamTransformerBase<String, dynamic> {
static final _openingBracketChar = '{'.codeUnitAt(0);
static final _closingBracketChar = '}'.codeUnitAt(0);
@override
Stream<dynamic> bind(Stream<String> stream) async* {
final sb = StringBuffer();
var bracketsCount = 0;
await for (final string in stream) {
for (var i = 0; i < string.length; i++) {
final current = string.codeUnitAt(i);
sb.writeCharCode(current);
if (current == _openingBracketChar) {
bracketsCount++;
}
if (current == _closingBracketChar && --bracketsCount == 0) {
yield json.decode(sb.toString());
sb.clear();
}
}
}
}
}
这篇关于Dart从不可编辑的大文件中读取JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!