JSON Tools – which will help you

JSON (JavaScript Object Notation) is a text-based information interchange format extensively utilized for net purposes. Compared with XML, it’s extra concise and takes up much less house. As well as, all browsers have built-in instruments for working with JSON.

The necessity to work with this format on the platform stage is due not solely to the truth that it’s a “modern fashionable” format that 1C: Enterprise utilized options themselves can use to combine with third-party purposes. One more reason is that JSON is used actively in HTTP interfaces. And in 1C: Enterprise, there are such mechanisms wherein you need to use this format. They’re a REST utility interface that’s robotically generated by the framework and HTTP providers that you can create yourself.

We see several predominant use instances for JSON.

First, it’s integration with exterior techniques using their HTTP interfaces: Google Calendar, Salesforce.com, 1C: Enterprise REST interface, SharePoint, and so on.

Secondly, it’s the group of its HTTP interface for the applying resolution.

Third, the trade of JSON information with exterior techniques. Formation of configuration tuning information. We utilize them in information trade procedures, for instance, with online shops.

Fourth is using JSON information to trade between completely different 1C: Enterprise purposes.

We have now applied several layers of labour within the platform with JSON. The best and most versatile are the low-level streaming, writing and studying instruments. Larger-level and never so familiar – the technique of serialization in JSON of primitive sorts and 1C: Enterprise collections.

Streaming, studying and writing JSON.

Streaming objects are generic JSON Learn and JSON Author objects. They learn JSON sequentially from a file or string or write JSON to a file or line. Thus, studying and writing JSON happens without producing the whole doc in reminiscence.

The next instance can be utilized as an instance streaming JSON studying:

Once you write JSON, you form its construction yourself. To “hedge” you towards errors, the JSON Document object robotically checks that the building being written is appropriate. To extend the velocity of labour, this examination could be disabled. Within the instance beneath, that is the road:

Additionally, when writing, you’ll be able to manage some parameters of the generated textual content, for example, using double quotes, line breaks, indentation characters, and character escaping. The representative beneath makes use of a tab character to format textual content:

A streaming JSON document would possibly appear like the next. An array of 4 components is written. Three of them are of a primitive kind, and a fourth factor is an object with two properties:

The results of such an entry:

{
	"СвойствоТипаМассив": [
		"Значение строка",
		1.2345E1,
		true,
		{
			"СвойствоТипаСтрока": "Значение строка",
			"СвойствоТипаНеопределено": null
		}
	]
}

Serializing primitive sorts and collections to JSON

The second group of instruments for working with JSON is friendly in that it saves you the trouble of studying/writing every particular person worth or property. When learning, JSON paperwork is mapped to a set of platform sorts: String, Quantity, Boolean, Undefined, Array, FixedArray, Construction, FixedStructure, Compliance, Date. Accordingly, in the wrong way, the composition of objects of those sorts lets you type in reminiscence and write a JSON construction to a file. Thus, studying and writing a small JSON of a previously identified building could be achieved with just a few strains of code.

We see the primary function of those instruments within the trade of knowledge with exterior techniques, studying configuration information in JSON format.

You’ll be able to carry out serialization utilizing the ReadJSON () and WriteJSON () strategies of the worldwide context. They work at the side of the JSON Learn and JSON Author objects.

For instance of JSON deserialization, contemplate studying an array of two objects:

[
	{
		"имя": "Anton",
		"фамилия": "Иванов",
		"возраст": 25
	},
	{
		"имя": "Ирина",
		"фамилия": "Иванова",
		"возраст": 20
	}
]

The 1C: Enterprise code that performs deserialization might appear like this:

And an example of serialization (writing) to JSON would possibly seem like this:

Recording result:

{
	"Фамилия": "Иванов",
	"Имя": "Иван",
	"Отчество": "Иванович",
	"Возраст": 40,
	"Женат": true,
	"Телефоны": [
		"8-999-999-99-90",
		"8-999-999-99-91"
	]
}

Serialization conversion and restoration features

Serialization might not all the time be achieved utterly robotically. There are several conditions in life. Due to this fact, we added the flexibility to use a “self-written” operation to deal with values ​​when writing to JSON and when studying from JSON.

Within the WriteJSON () methodology, it’s referred to as Conversion Perform and is described utilizing three parameters:

  • TransformFunctionName;
  • ModuleFunctionsConversions;
  • AdditionalParametersFunctionsTransformations.

Within the ReadJSON () methodology, it’s referred to as the Restore Perform, and there are comparable parameters for it:

  • RecoveryFunctionName;
  • Restoration Perform Module;
  • AdditionalParametersRestoration Perform.

When writing to JSON, this characteristic is beneficial as a result, and it lets you convert to JSON these sorts that aren’t topic to automated conversion. And even refuse to serialize them altogether.

For instance, it turned out that within the construction being written, one of many values ​​is a hyperlink to a component of the Organizational Departments catalogue. Such a worth (a reference to a 1C: Enterprise object) can’t be robotically serialized by the platform. Then, utilizing the conversion operation, we will get a handy type for this worth its string illustration. For instance, within the style of a line “IE Petrov: Promoting Division”,,.

Instance execution result:

{
	"Фамилия": "Иванов",
	"Имя": "Иван",
	"Отчество": "Иванович",
	"Подразделение": "ИП Петров: Отдел рекламы",
	"Телефоны": [
		"8-999-999-99-90",
		"8-999-999-99-91"
	]
}

When studying JSON, the restoration operates can transform JSON information into 1C sorts, which can’t be the results of automated conversion, or independently (not robotically) convert JSON dates to 1C: Enterprise dates.

Serialization kind Date

Knowledge of the Date kind is serialized to JSON robotically; however, the reverse conversion (deserialization) might not be carried out. JSON doesn’t include the Date kind, and date values ​​are represented as a string. There are some codecs for representing dates, however typically talking, the looks of such a string could be very numerous.

To serialize the Date kind to JSON within the WriteJSON () methodology, you need to use the Serialization Settings parameter. It’s an embedded language object that lets you specify wherein variant the date might be written (UTC, native date, or offset native date) and wherein format (ISO, JavaScript, or Microsoft).

Code 1C: Enterprises:

JSON textual content:

[
	{
		"Фамилия": "Иванов",
		"ДатаРождения": "1987-05-14T00:00:00"
	},
	{
		"Фамилия": "Петров",
		"ДатаРождения": "1993-11-21T00:00:00"
	}
]

When studying a date from JSON, issues are extra sophisticated. Within the PropertyNameSetValuesDate parameter, you’ll be able to list these JSON properties whose values ​​must be transformed to a 1C: Enterprise date (Date kind). And within the ExpectedDateFormat parameter, you’ll want to specify what format this information is contained in JSON (ISO, JavaScript or Microsoft).

JSON textual content:

[
	{
		"Фамилия": "Иванов",
		"ДатаРождения": "1987-05-14T00:00:00"
	},
	{
		"Фамилия": "Петров",
		"ДатаРождения": "1993-11-21T00:00:00"
	}
]

Code 1C: Enterprises:

Nevertheless, if it seems that sooner or later, the JSON information format doesn’t match the anticipated design, an exception might be thrown.

In such a state of affairs, for more considerable versatility, you’ll be able to embrace the identical JSON properties in an array to be processed by the Restore operate – PropertyNamesForRestoreProcessing. And already within the Restore work, you deserialize the JSON dates, no matter what format.

Utilizing JSON in HTTP Utility Interfaces

Routinely generated REST interface for utilized options

When accessing the REST interface of the applying resolution, you’ll be able to obtain a response in JSON format. To do that, you’ll want to specify the $ format = JSON parameter within the tackle bar. Or select the MIME kind “utility / JSON” within the Settle for HTTP request header. As an illustration:

Inquiry:

GET /TestInfobase/odata/normal.odata/СправочникДляТестов?$format=json HTTP/1.1
MaxDataServiceVersion: 3.0;NetFx
Settle for: utility/json
Settle for-Charset: UTF-8
Consumer-Agent: Microsoft ADO.NET Knowledge Providers

Reply:

HTTP/1.1 200 OK
Content material-Size: 9429
Content material-Sort: utility/json;charset=utf-8
Server: Microsoft-IIS/7.5
DataServiceVersion: 3.0
X-Powered-By: ASP.NET
Date: Mon, 12 Aug 2013 09:44:07 GMT
    
{
"odata.metadata":"http://host/svc/$metadata#СправочникДляТестов",
"worth":[
{
	"Ref_Key":guid'cc6a7df3-8cfe-11dc-8ca0-000d8843cd1b',
	"DataVersion":"AAAAAQAAAAE",	
	"DeletionMark":false,
	"Parent_Key":guid'bbb079ae-8c51-11db-a9b0-00055d49b45e',
	"IsFolder":false,
	"Code":000000025,
	"Description":"Пинетки",
	"Поставщик_Key":guid'd1cb82a7-8e8b-11db-a9b0-00055d49b45e',
	"Поставщик@navigationLinkUrl":"СправочникДляТестов(guid'cc6a7df3-8cfe-11dc-8ca0-000d8843cd1b')/Поставщик",
	"РеквизитХранилище_Type": "image/jpeg",
	"РеквизитХранилище[email protected]": "Catalog_ДемоСправочник(guid'cf2b1a24-1b96-11e3-8f11-5404a6a68c42')/РеквизитХранилище_Base64Data",
	"РеквизитХранилище_Base64Data": <строка с закодированными данными>
	…
},
{…},
{…}
]
}

You’ll be able to manage the quantity of knowledge transferred by altering the elements of the metadata presentation within the ad. There are three tiers: Nometadata, Minimalmetadata, and Full metadata. By default (within the instance above), the centre stage is used – Minimalmetadata. On the Nometadata stage, the quantity of transmitted info is minimal, and on the Fullmetadata stage, the utmost. Nevertheless, it needs to be understood that lowering the number of transmitted info results in extra intensive calculations on the consumer. Conversely, when all the data is included within the ad, the quantity of computation on the consumer might be minimal.

You’ll be able to specify the element of metadata presentation, for instance, within the tackle bar.

Metadata info just isn’t transferred:

GET /TestInfobase/odata/normal.odata/СправочникДляТестов/?$format=utility/json;odata= minimalmetadata

All metadata info is included within the add:

GET /TestInfobase/odata/normal.odata/СправочникДляТестов/?$format=utility/json;odata=fullmetadata

Utility resolution HTTP providers

HTTP providers applied in a utility resolution may also return a response in JSON format. To do that, the most straightforward means is to type the physique of the response in JSON and get it as a string, after which set the shape of the HTTP response of the service from this string. Nevertheless, it’s advisable to point out that the BOM (Byte Order Mark) shouldn’t be used.

The final parameter (UsingByteOrderMark.Don’t use) you’ll be able to go away off if the configuration compatibility mode just isn’t set, or it’s larger than Version8_3_5. As a result of this case, the BOM will robotically be used just for UTF-16 and UTF-32 encodings and for UTF-8, UTF-16LE / UTF-16BE, UTF-32LE / UTF-32BE and others, it is not going to be used.

Interplay with third-party HTTP providers

When interacting with third-party HTTP interfaces, you might also type requests to them in JSON format. In this case, the algorithm of your actions would be identical. Kind the request physique in JSON. You get the body as a string. From this line, set the form of the HTTP request. Do not use the BOM.

Additional improvement

We’re excited about offering you the flexibility to serialize 1C: Enterprise utility sorts in JSON: hyperlinks, objects, recordsets, and so on. Due to this fact, there’s a chance of the looks of one other, third stage of instruments for working with JSON. This stage will permit you to convert any 1C: Enterprise sorts to JSON, for which XDTO serialization to XML is supported.

Facebook
Twitter
Pinterest
WhatsApp

Related Articles

Latest Articles