Комментарии 8
он достигает уже 100+МБ/с. Понятия не имею, в чём причина. Использование sudo значительно ускоряет скорость парсера.
Судя по отметке в 100 Mbps, больше похожей на типовое значение пропускной способности SSD, дело не в скорости парсинга (она должна быть на порядок выше этого значения даже на наивном парсере), а в том, что в тесте смешиваются скорость парсинга и скорость чтения с диска, и бутылочным горлышком является как раз i/o. При повторном запуске программа вероятно попадает в дисковый кэш. Sudo здесь ни при чём
видел пример с парсер комбинаторами - для json они хорошо работают
Кто с гроком общался, тот в цирке не смеется. Спросил его какие есть подходы в парсинге json (переводить не буду, теряется стиль). Его ответ (прикольное - Manual Parsing If you’re a masochist):
Approaches to Parsing JSON
Built-in Language Parsers Most modern programming languages come with standard libraries to handle JSON parsing, making this the go-to for simplicity.
How it works: You pass the JSON string to a built-in function or method, and it spits out a native data structure.
Examples:
Python: json.loads() turns a string into a dict, list, etc.
JavaScript: JSON.parse() gives you an object or array.
Java: Libraries like org.json or Gson map JSON to objects.
Pros: Fast, reliable, no external dependencies.
Cons: Limited customization; you’re stuck with the language’s defaults.
Manual Parsing If you’re a masochist or working in a language without a JSON parser, you could write your own.
How it works: You tokenize the string (split it into pieces like {, "key", :, etc.), then build a data structure by interpreting those tokens according to JSON’s grammar rules.
Pros: Total control; useful for learning or super-specific needs.
Cons: Time-consuming, error-prone, and why reinvent the wheel?
Streaming Parsers For huge JSON files or real-time data (like logs or API streams), you don’t want to load everything into memory at once.
How it works: The parser reads the JSON incrementally, firing events or callbacks as it encounters elements (e.g., "start of object," "key-value pair").
Examples:
Python: ijson for event-driven parsing.
Java: Jackson’s JsonParser for streaming.
JavaScript: Libraries like JSONStream.
Pros: Memory-efficient for big data.
Cons: More complex to code; you’re handling pieces, not the whole picture.
Schema-Driven Parsing Sometimes you want to enforce a structure or validate the JSON against a blueprint (schema) before parsing.
How it works: Define a schema (e.g., JSON Schema), validate the JSON, then parse it into typed objects.
Examples:
Python: jsonschema for validation, paired with pydantic for object mapping.
Java: Jackson or Gson with annotations.
TypeScript: Tools like zod or io-ts for type-safe parsing.
Pros: Strong typing, error checking upfront.
Cons: Extra setup; overkill for simple tasks.
Tools and Libraries
The ecosystem of JSON tools is massive, and your choice depends on language and use case. Here’s a rundown of popular ones:
Python:
json (standard library): Basic but solid.
pydantic: Parse into typed models with validation.
ijson: Streaming for big files.
JavaScript:
JSON.parse(): Built-in, no fuss.
JSONStream: Streaming for Node.js.
ajv: Fast schema validation.
Java:
Gson (Google): Simple, maps JSON to POJOs (Plain Old Java Objects).
Jackson: Powerful, supports streaming and customization.
org.json: Lightweight, bare-bones option.
C#:
Newtonsoft.Json (Json.NET): The gold standard, feature-rich.
System.Text.Json: Built-in, leaner alternative.
Command-Line Tools:
jq: Parse and manipulate JSON in scripts or terminal (e.g., cat data.json | jq '.name').
jsonlint: Validate JSON syntax.
Думал, какой-то новичок-студент решил поделиться простым проектом на Rust в качестве первой статьи, а это перевод. Не очень понимаю, для чего переводить такие материалы. Есть куча статей на две головы выше этой
Парсер JSON в 500 строках Rust