Skip to content

Исправлена ошибка при чтении строк, содержащих дату в формате ISO 8601, при использовании объекта ЧтениеJSON и глобальной функции ПрочитатьJSON: строки с датой больше не преобразуются в Дату автоматически#1682

Open
leemuar wants to merge 7 commits into
EvilBeaver:developfrom
leemuar:fix-readerjson-date-parsing

Conversation

@leemuar
Copy link
Copy Markdown

@leemuar leemuar commented May 16, 2026

Внутренняя реализация чтения json использовала популярную библиотеку работы с json от newtonsoft.
Эта библиотека по-умолчанию преобразует в тип Дата строки, содержащие дату в формате ISO - "2026-05-13T22:51:46.230Z". Из-за этого поведение объекта ЧтениеJSON и функии ПрочитатьJSON() отличалось от платформы 1С:

  • ПрочитатьJSON() автоматически преобразовывало такие значения в тип Дата. С одной стороны это удобно, но с другой стороны эту конвертацию никак не отключить если она не нужна, и - самое важное - ISO-дата могла содержать микросекунды, которые при конвертации в Дату терялись (т.к. Дата в 1С не содержит микросекунд)
  • ЧтениеJSON при чтении такого значения в свойстве ТипТекущегоЗначения устанавливало "Ничего", а должна быть "Строка". Это мешает написать свой парсер без автоконвертации дат

Возврат поведения к идиоматическому платформенному позволит обрабатывать json свободно, писать свои алгоритмы преобразования дат при использовании последовательного чтения с помощью ЧтениеJSON и пр. Сейчас это невозможно, точное значение даты может теряться при автоматической конвертации рантаймом.

Важно! Это может быть breaking change если какой-то код заложился на этот баг - когда строка с датой автоматически преобразуется в тип Дата функцией ПрочитатьJSON(). Но имхо "типовое" поведение важнее иметь

Summary by CodeRabbit

  • Bug Fixes

    • ISO-8601 datetime values in JSON are now preserved as strings (no automatic date conversion).
  • Tests

    • Added tests verifying ISO-8601 datetime strings are read unchanged across file, stream, in-memory, sequential reads, and fractional-second variants.

Review Change Stack

leemuar added 2 commits May 16, 2026 10:30
Исправлено поведение объекта ЧтениеJSON и глобальной функции ПрочитатьJSON, строки с датами не конвертируются автоматически в дату
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 16, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 24f68d69-70f0-43d7-b2e2-fd155105f305

📥 Commits

Reviewing files that changed from the base of the PR and between 4c9ee3c and 43c3809.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/json/test-json_reader.os

📝 Walkthrough

Walkthrough

JSONReader now sets SupportMultipleContent and disables Newtonsoft date parsing inside its internal reader. Tests and a fixture were added to confirm ISO-8601 timestamps are read and preserved as strings from string, stream, and file sources.

Changes

ISO-8601 Datetime String Handling

Layer / File(s) Summary
Configure JsonReaderInternal (date parsing & multi-content)
src/OneScript.StandardLibrary/Json/JSONReader.cs
JsonReaderInternal constructor sets SupportMultipleContent = true and DateParseHandling = DateParseHandling.None; OpenFile, OpenStream, and SetString now instantiate JsonReaderInternal without caller-side initializers.
Tests and fixture for ISO datetime as string
tests/json/test-json_reader.os, tests/json/json-mock_isodate.json
Added five exported test procedures covering token sequence, current-value checks, structured parsing via ПрочитатьJSON, stream reading, and file reading; updated fixture lastSignInTime to "2026-05-13T22:51:46Z".

Sequence Diagram

sequenceDiagram
  participant JSONInput as JSON Input
  participant JSONReader as JSONReader
  participant JsonReaderInternal as JsonReaderInternal
  participant TestConsumer as Test/Consumer
  JSONInput->>JSONReader: provide JSON with ISO-8601 string
  JSONReader->>JsonReaderInternal: construct internal reader (SupportMultipleContent=true, DateParseHandling=None)
  JsonReaderInternal->>TestConsumer: emit token as String (not Date)
  TestConsumer->>TestConsumer: assert value and type are String
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • nixel2007

Poem

🐰 I nibbled through JSON late at night,

Found dates that tried to change their sight,
I whispered "None" to parser's art,
And kept each ISO string a part,
Hooray — tests hop happy, pure and bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: fixing a bug where ISO 8601 date strings in JSON are no longer automatically converted to Date type when using JSONReader and ПрочитатьJSON function, bringing behavior in line with 1С platform.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
tests/json/test-json_reader.os (1)

265-333: ⚡ Quick win

Add ISO-string regression tests for ОткрытьФайл and ОткрытьПоток.

These new tests cover УстановитьСтроку, but this PR also changes initialization in file/stream entrypoints. Adding one focused case per path will lock the behavior across all three constructors.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/json/test-json_reader.os` around lines 265 - 333, The tests only
exercise УстановитьСтроку but the PR changed initialization paths for
file/stream entrypoints (ОткрытьФайл, ОткрытьПоток), so add parallel regression
tests that mirror Тест_Должен_ОпределятьСтрокуСДатойВФорматеISOКакСтроку,
Тест_Должен_ЧитатьСтрокуСДатойВФорматеISOКакСтроку and
Тест_Должен_ЧитатьДатуВФорматеISOКакСтрокуПриИспользованииПрочитатьJSON but
using ЧтениеJSON created via ОткрытьФайл(...) and ОткрытьПоток(...) (and their
corresponding close semantics) to assert the same sequence of
ТипТекущегоЗначения and that ТекущееЗначение/ПрочитатьJSON preserve ISO
timestamps as strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/json/test-json_reader.os`:
- Around line 265-333: The tests only exercise УстановитьСтроку but the PR
changed initialization paths for file/stream entrypoints (ОткрытьФайл,
ОткрытьПоток), so add parallel regression tests that mirror
Тест_Должен_ОпределятьСтрокуСДатойВФорматеISOКакСтроку,
Тест_Должен_ЧитатьСтрокуСДатойВФорматеISOКакСтроку and
Тест_Должен_ЧитатьДатуВФорматеISOКакСтрокуПриИспользованииПрочитатьJSON but
using ЧтениеJSON created via ОткрытьФайл(...) and ОткрытьПоток(...) (and their
corresponding close semantics) to assert the same sequence of
ТипТекущегоЗначения and that ТекущееЗначение/ПрочитатьJSON preserve ISO
timestamps as strings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: cbb85473-a4a9-40d4-bb39-90c64570a5c5

📥 Commits

Reviewing files that changed from the base of the PR and between d201b54 and 8efa13e.

📒 Files selected for processing (2)
  • src/OneScript.StandardLibrary/Json/JSONReader.cs
  • tests/json/test-json_reader.os

@leemuar leemuar changed the title Исправлена ошибка при чтении строк, содержащих дату в формате ISO 8601, при использовании объекта ЧтениеJSON и глобальной функции ПрочитатьJSON Исправлена ошибка при чтении строк, содержащих дату в формате ISO 8601, при использовании объекта ЧтениеJSON и глобальной функции ПрочитатьJSON: строки с датой больше не преобразуются в Дату автоматически May 16, 2026
@leemuar leemuar marked this pull request as draft May 16, 2026 09:13
@leemuar leemuar marked this pull request as ready for review May 16, 2026 10:18
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/json/test-json_reader.os`:
- Around line 359-375: В тестовой процедуре
Тест_Должен_ОткрытьФайлЧитаетСтрокуСДатойВФорматеISOКакСтроку() используется
переменная Чтение для создания экземпляра JSON-ридера, но далее вызываются
методы у неинициализированной переменной ЧтениеJSON; исправьте это, заменив все
вызовы ЧтениеJSON.Прочитать(), ЧтениеJSON.ТекущееЗначение,
ЧтениеJSON.ТипТекущегоЗначения и ЧтениеJSON.Закрыть() на эквивалентные вызовы
через Чтение (т.е. Чтение.Прочитать(), Чтение.ТекущееЗначение,
Чтение.ТипТекущегоЗначения, Чтение.Закрыть()) либо инициализируйте ЧтениеJSON =
Новый ЧтениеJSON перед использованием, если вы намеренно хотите использовать
переменную ЧтениеJSON.
- Around line 267-292: Тест
Тест_Должен_ОпределятьСтрокуСДатойВФорматеISOКакСтроку собирает ожидаемые и
фактические последовательности в ЭталонЗначения и ФактЗначения, но не проверяет
их длину, поэтому лишние токены пройдут незамеченными; добавьте в процедуру до
цикла сравнения явную проверку размера массивов (например через Колво() или
ВГраница+1) с использованием юТест.ПроверитьРавенство, чтобы убедиться, что
ФактЗначения и ЭталонЗначения имеют одинаковую длину перед посекторным
сравнением, затем оставить существующий цикл сравнения по индексам.
- Around line 333-357: The test currently opens a stream on the reader instance
named Чтение but then performs reads and assertions on a different reader
ЧтениеJSON, so ОткрытьПоток is never actually verified; fix by using the same
reader instance (Чтение) for
Прочитать/ТекущееЗначение/ТипТекущегоЗначения/Закрыть or remove the unused
ЧтениеJSON setup and instead call УстановитьСтроку only on Чтение if needed;
ensure the assertions reference Чтение and its ТипТекущегоЗначения so the
ОткрытьПоток call is actually exercised (look for symbols:
Тест_Должен_ОткрытьПотокЧитаетСтрокуСДатойВФорматеISOКакСтроку, Чтение,
ЧтениеJSON, ОткрытьПоток, УстановитьСтроку, Прочитать).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 04826260-11e9-47e7-9062-eacb1d66c62e

📥 Commits

Reviewing files that changed from the base of the PR and between 8efa13e and 4c9ee3c.

📒 Files selected for processing (2)
  • tests/json/json-mock_isodate.json
  • tests/json/test-json_reader.os
✅ Files skipped from review due to trivial changes (1)
  • tests/json/json-mock_isodate.json

Comment thread tests/json/test-json_reader.os
Comment thread tests/json/test-json_reader.os
Comment thread tests/json/test-json_reader.os
Comment on lines +302 to +303
SupportMultipleContent = true
,DateParseHandling = DateParseHandling.None
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обе эти инициализации во всех трех местах стоит перенести в конструктор JsonReaderInternal

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправлено. Ошибки в тестах тоже исправлены

@leemuar leemuar marked this pull request as draft May 16, 2026 17:24
@leemuar leemuar marked this pull request as ready for review May 16, 2026 19:32
@EvilBeaver
Copy link
Copy Markdown
Owner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants