JSON in 1C:Enterprise: read, write, HTTP requests and common errors
Checkcraft is a desktop app for checking APIs and logs without code, with a free edition. Download, no sign-up →
In 1C:Enterprise 8.3 JSON is read with the JSONReader object and the ReadJSON function and written with JSONWriter and WriteJSON. Below are working samples: string to Structure, Structure to string, files, an HTTP request with a JSON body, dates and the usual integration errors.
How to read JSON in 1C
Create a JSONReader, give it a string with SetString or a file with OpenFile, and call ReadJSON. The second parameter decides the result: False gives a Structure, True gives a Map. A Map is safer, because JSON keys such as order-id or 1st cannot be Structure property names.
How to write JSON in 1C
Create a JSONWriter, call SetString for a string or OpenFile for a file, then WriteJSON with the value and Close. Close returns the ready string. You can write a Structure, a Map with string keys, an Array, strings, numbers, booleans and Undefined, which becomes null.

How to send JSON in an HTTP request
Build the string with JSONWriter, create an HTTPRequest with the resource path, add the Content-Type: application/json header and set the body with SetBodyFromString in UTF-8 without a BOM. POST is sent with Post, other methods with CallHTTPMethod. Check the status code and content type before reading the JSON.
Why another system rejects JSON from 1C
Usually one of three things: a BOM at the start of the body, dates in a format the other side does not expect, and numbers written as strings. Compare what you sent with the partner's documented example. A JSON validator and a simple JSON diff are the fastest way.

How to check a JSON exchange regularly
A one-off check in the debugger guarantees nothing for the next release. Save the request to the HTTP service or partner together with rules: status code, required fields, totals, no errors in the exchange log. After each configuration update the check repeats with one click.
Example: JSON string to Map
ЧтениеJSON = Новый ЧтениеJSON;
ЧтениеJSON.УстановитьСтроку(СтрокаJSON);
Данные = ПрочитатьJSON(ЧтениеJSON, Истина); // Истина: Соответствие, Ложь: Структура
ЧтениеJSON.Закрыть();
Итог = Данные.Получить("total");
Для Каждого Позиция Из Данные.Получить("items") Цикл
Сообщить(Позиция.Получить("sku"));
КонецЦикла;Reading into a Structure (second parameter False) lets you use dot access, but any key with a dash, space or leading digit breaks reading. For other services' responses use a Map.
Example: Structure to JSON string
Заказ = Новый Структура;
Заказ.Вставить("id", 5001);
Заказ.Вставить("status", "NEW");
Позиции = Новый Массив;
Позиция = Новый Структура("sku, qty", "A-1", 2);
Позиции.Добавить(Позиция);
Заказ.Вставить("items", Позиции);
ЗаписьJSON = Новый ЗаписьJSON;
ЗаписьJSON.УстановитьСтроку(Новый ПараметрыЗаписиJSON(ПереносСтрокJSON.Нет));
ЗаписатьJSON(ЗаписьJSON, Заказ);
СтрокаJSON = ЗаписьJSON.Закрыть(); // {"id":5001,"status":"NEW","items":[{"sku":"A-1","qty":2}]}ПереносСтрокJSON.Нет (no line breaks) gives a compact string for sending. For logs and debugging ПереносСтрокJSON.Авто indents the JSON.
Reading and writing a JSON file
// запись в файл
ЗаписьJSON = Новый ЗаписьJSON;
ЗаписьJSON.ОткрытьФайл("C:\Обмен\order.json", "UTF-8");
ЗаписатьJSON(ЗаписьJSON, Заказ);
ЗаписьJSON.Закрыть();
// чтение из файла
ЧтениеJSON = Новый ЧтениеJSON;
ЧтениеJSON.ОткрытьФайл("C:\Обмен\order.json");
Данные = ПрочитатьJSON(ЧтениеJSON, Истина);
ЧтениеJSON.Закрыть();POST with JSON via HTTPConnection
Соединение = Новый HTTPСоединение("api.example.com", 443, , , , 30, Новый ЗащищенноеСоединениеOpenSSL);
Запрос = Новый HTTPЗапрос("/api/orders");
Запрос.Заголовки.Вставить("Content-Type", "application/json");
Запрос.Заголовки.Вставить("Authorization", "Bearer " + Токен);
Запрос.УстановитьТелоИзСтроки(СтрокаJSON, "UTF-8", ИспользованиеByteOrderMark.НеИспользовать);
Ответ = Соединение.ОтправитьДляОбработки(Запрос); // POST
ТипОтвета = Ответ.Заголовки.Получить("Content-Type");
ТелоОтвета = Ответ.ПолучитьТелоКакСтроку("UTF-8");
Если Ответ.КодСостояния <> 201 Тогда
ВызватьИсключение СтрШаблон("Код %1, тело: %2", Ответ.КодСостояния, Лев(ТелоОтвета, 200));
КонецЕсли;Set the third parameter of SetBodyFromString explicitly. A BOM at the start of the body is a common reason a partner service answers 400 or cannot parse the request. To see exactly what is sent, repeat the request with curl, see curl POST with JSON.
Dates in JSON and 1C
// чтение: поля created и paidAt превратятся в Дату
Данные = ПрочитатьJSON(ЧтениеJSON, Истина, "created,paidAt", ФорматДатыJSON.ISO);
// запись: даты в ISO 8601
Настройки = Новый НастройкиСериализацииJSON;
Настройки.ФорматСериализацииДаты = ФорматДатыJSON.ISO;
ЗаписатьJSON(ЗаписьJSON, Заказ, Настройки);Without the property names dates stay strings. If the partner sends times with a time zone, agree which zone to store, or a three-hour shift will show up in reports.
JSON and 1C types
| JSON | Read in 1C as | Mind |
|---|---|---|
| object {} | Structure or Map | Map for keys with dashes or digits |
| array [] | Array | Order is kept |
| string | String | A date stays a string unless listed |
| number | Number | Money comes as a fraction, round explicitly |
| true, false | Boolean | The string "true" is not a boolean |
| null | Undefined | Tell it apart from a missing key |
Checking a 1C JSON exchange from outside
- Send a request to the 1C HTTP service (a /hs/... path) with curl or an API client and look at status, headers and body.
- Compare the response with the contract: required fields, types, totals.
- Check that a partner error comes as clear JSON, not an HTML page.
- Save these checks and repeat them after every configuration update.
If the response does not parse, start with unexpected character when reading JSON.
More on 1C
Section overview and all guides: 1C integration via API: options, architecture and examples.
- Unexpected character when reading JSON in 1C: causes and fixes
- Structure, Array and ValueTable to JSON in 1C: both directions
- Data exchange in 1C: methods, formats, setup and checks
- Integrating 1C with a website and online store: options and pitfalls
- Automated testing in 1C: Vanessa Automation, YAxUnit and integration checks
Frequently asked questions
How do I read JSON into a Structure in 1C?
Create a JSONReader, call SetString with the JSON and ReadJSON(reader, False). If keys contain dashes or start with digits, read into a Map with ReadJSON(reader, True).
How do I write a Structure to a JSON string in 1C?
Create a JSONWriter, call SetString, then WriteJSON(writer, structure) and Close, which returns the string.
How do I POST JSON from 1C?
Create an HTTPConnection and HTTPRequest, add Content-Type: application/json, call SetBodyFromString with UTF-8 and no BOM, then Post.
How do I read a date from JSON in 1C?
Pass the date field names as the third ReadJSON parameter and the format as the fourth, for example ISO. Otherwise dates stay strings.
Repeat this on your own API
Checkcraft is a desktop app that saves API response checks without code and shows what did not match. Start with a sample, then use your own sanitized data. Free runs on Windows and Linux with no time limit.
Download FreeDownload and first runNo sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.
References
Start with the linked example and compare its result with your own test requirement.