• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Transform JSON with JOLT in JavaScript?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Introduction to JSON Transformation with JOLT


If you are working with JSON data, you may find the need to transform payloads for various operations such as API responses, data processing, or frontend display. In this article, we will explore how to use JOLT, a powerful JSON transformation tool, to achieve a specific transformation based on matching values between two JSON payloads. The example we'll delve into will show how to extract mobile numbers from a larger JSON structure based on specific criteria.

Understanding the JSON Structure


Here’s the JSON payload we'll start with:

{
"firstPayload": {
"contactNumber": [
{
"id": "1",
"mobileNum": "+447665463628",
"mobileMask": "+44******628",
"contactType": "mobile"
},
{
"id": "2",
"mobileNum": "+447665463111",
"mobileMask": "+44******111",
"contactType": "mobile"
},
{
"id": "3",
"mobileNum": "+447665463333",
"mobileMask": "+44******333",
"contactType": "mobile"
},
{
"id": "4",
"mobileNum": "+440674232123",
"mobileMask": "+44******123",
"contactType": "landline"
}
]
},
"secondPayload": {
"contactNumber": [
{
"id": "1",
"mobileMask": "+44******628",
"contactType": "mobile"
}
]
}
}


In the above JSON, we have two payloads: firstPayload with multiple contact numbers and secondPayload containing a single contact number that we will use for matching.

Why Use JOLT for JSON Transformation?


JOLT is an JSON transformation library designed to allow you to manipulate JSON structures easily and succinctly. It enables you to create a blueprint of the desired output format using a simple JSON format. This approach can save time and reduce complexity in handling JSON data.

Step-by-Step JOLT Transformation


To achieve the desired output {"mobileNum" : "+447665463628"} from the above payloads based on the exact match of id, we can set up a JOLT specification as follows:

Defining the JOLT Specification


We will first create a transform spec in JSON format. Here’s how:

[
{
"operation": "shift",
"spec": {
"firstPayload": {
"contactNumber": {
"*": {
"id": {
"@": "matched.@",
"id": "$.mobileNum"
}
}
}
},
"secondPayload": {
"contactNumber": {
"*": {
"id": "$.matched.id"
}
}
}
}
},
{
"operation": "remove",
"spec": {
"matched": {
"id": "*"
}
}
}
]


This specification effectively does two things:

  • Shift: It matches the id from secondPayload with the id from all entries in firstPayload. If they match, we keep the mobileNum in an output field.
  • Remove: After the data has been shifted to the desired format, we clean up unnecessary fields from the output.
Applying the JOLT Specification in JavaScript


Now, let's see how to apply this JOLT transformation in JavaScript using the jolt-transformer library. First, make sure you have it installed:

npm install jolt-transformer


Next, use the following JavaScript code to perform the transformation:

const jolt = require('jolt-transformer');

const inputPayload = {
"firstPayload": { ... }, // Insert your firstPayload here
"secondPayload": { ... } // Insert your secondPayload here
};

const joltSpec = [
{ "operation": "shift", "spec": { ... } }, // Insert your shift specification here
{ "operation": "remove", "spec": { ... } } // Insert your remove specification here
];

const transformedOutput = jolt.Transform(inputPayload, joltSpec);
console.log(JSON.stringify(transformedOutput));


Replace ... in the above code with the actual content of firstPayload, secondPayload, and the JOLT specifications we defined earlier.

Expected Output


When you run the script above with the correct JOLT specification and the JSON payloads, the expected output should be:

{"mobileNum" : "+447665463628"}

Frequently Asked Questions (FAQ)

What is JOLT?


JOLT is a JSON transformation library that allows for the easy retrieval and transformation of data stored in JSON format.

Can JOLT handle deeply nested JSON?


Yes, JOLT can manage complex JSON structures, allowing for intricate modifications and transformations under various conditions.

Do I need to use Node.js to run JOLT?


While this example uses Node.js, JOLT can also be used in browser environments with proper setup.

Conclusion


In this article, we explored how to transform JSON payloads using JOLT based on specific conditions. This powerful library can streamline your JSON processing tasks significantly. Whether you're working with simple or complex JSON structures, learning to use JOLT effectively can provide you with efficient solutions for your data transformation needs.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу