Created
May 17, 2023 20:34
-
-
Save PlugFox/621a381f29ea9ce49eeebb025e516153 to your computer and use it in GitHub Desktop.
Dart SimpleJsonParser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SimpleJsonParser { | |
int _index = 0; | |
final String _json; | |
SimpleJsonParser(this._json); | |
dynamic parse() { | |
final value = _parseValue(); | |
while (_index < _json.length && _json[_index].trim().isEmpty) { | |
_index++; | |
} | |
if (_index < _json.length) { | |
throw Exception('Unexpected character at index $_index'); | |
} | |
return value; | |
} | |
dynamic _parseValue() { | |
_skipWhitespace(); | |
if (_index >= _json.length) throw Exception('Unexpected end of input'); | |
final char = _json[_index]; | |
if (char == '{') return _parseObject(); | |
if (char == '[') return _parseArray(); | |
if (char == '"') return _parseString(); | |
if ('0123456789-'.contains(char)) return _parseNumber(); | |
throw Exception('Unexpected character at index $_index'); | |
} | |
void _skipWhitespace() { | |
while (_index < _json.length && _json[_index].trim().isEmpty) { | |
_index++; | |
} | |
} | |
Map<String, dynamic> _parseObject() { | |
_index++; // { | |
final map = <String, dynamic>{}; | |
while (_json[_index] != '}') { | |
final key = _parseString(); | |
_skipWhitespace(); | |
if (_json[_index] != ':') throw Exception('Expected : at index $_index'); | |
_index++; // : | |
final value = _parseValue(); | |
map[key] = value; | |
_skipWhitespace(); | |
if (_json[_index] == ',') _index++; | |
_skipWhitespace(); | |
} | |
_index++; // } | |
return map; | |
} | |
List<dynamic> _parseArray() { | |
_index++; // [ | |
final list = <dynamic>[]; | |
while (_json[_index] != ']') { | |
list.add(_parseValue()); | |
_skipWhitespace(); | |
if (_json[_index] == ',') _index++; | |
_skipWhitespace(); | |
} | |
_index++; // ] | |
return list; | |
} | |
String _parseString() { | |
_index++; // " | |
final start = _index; | |
while (_json[_index] != '"') { | |
_index++; | |
} | |
final string = _json.substring(start, _index); | |
_index++; // " | |
return string; | |
} | |
num _parseNumber() { | |
final start = _index; | |
while (_index < _json.length && '0123456789.-eE'.contains(_json[_index])) { | |
_index++; | |
} | |
final number = num.tryParse(_json.substring(start, _index)); | |
if (number == null) throw Exception('Invalid number at index $start'); | |
return number; | |
} | |
} | |
void main() { | |
final parser = SimpleJsonParser('{"key": "value", "key2": [1, 2, 3]}'); | |
print(parser.parse()); // {key: value, key2: [1, 2, 3]} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment