Я использую node.js для получения данных с веб-сайта. Когда у меня есть эти извлеченные данные, я хочу вставить их в базу данных mySQL. Получение URL-адреса дает мне дамп информации json.
После форматирования строки я использую массив для хранения своих данных. Ниже приведен пример моего вывода:
['table_id: 0xFC (252) SCTE 35',
"section_syntax_indicator: '0'",
"private_indicator: '0'",
"reserved: '11'",
'section_length: 0x39 (57)',
'protocol_version: 0',
'encrypted_packet: 0 no part of this message is encrypted',
'encryption_algorithm: 0 No encryption',
'pts_adjustment: 0xFFFF7F18 (33000) > Time: 95443.4 sec > (hh:mm:ss.ms) 26:30:43.351',
'cw_index: 0x00 (0)',
'tier: 0x0FFF (4095)',
'splice_command_length: 0x0005 (5)',
'splice_command_type: 0x06 (6) time_signal [] time_signal: > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'time_specified_flag: 1 presence of the pts_time field',
'reserved: 0x3F (63)',
'pts_time: PTS: 1741047514 [0x67C646DA] > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'descriptor_loop_length: 35 [] Descriptors: [] segmentation_descriptor (0x02): Content Identification (0x01)',
'descriptor_tag: 0x02 (2)',
'descriptor_length: 0x21 (33)',
'identifier: 0x43554549 (CUEI)',
'segmentation_event_id: 0x00000001 (1)',
"segmentation_event_cancel_indicator: '0' a previously sent segmentation event, identified by segmentation_event_id, has NOT been cancelled",
'reserved: 0x7F (127)',
"program_segmentation_flag: '1' the message refers to a Program Segmentation Point and that the mode is the Program Segmentation Mode whereby all PIDs/components of the program are to be segmented",
"segmentation_duration_flag: '0' No presence of segmentation_duration field",
"delivery_not_restricted_flag: '1' the next five bits are reserved",
'reserved: 0x1F (31)',
'segmentation_upid_type: 0x01 (1) Deprecated: use type 0x0C; The segmentation_upid does not follow a standard naming scheme.',
'segmentation_upid_length: 0x12 (18)',
'segmentation_type_id: 0x01 (1) Content Identification',
'segment_num: 0x01 (1)',
'segments_expected: 0x01 (1)',
'CRC_32: 0x46D15AF3 CRC OK'
]
Я хочу разделить каждый элемент этого массива на разные категории.
Например: "time_specified_flag: 1 presence of the pts_time field"
Я хочу, чтобы этот элемент был разделен на 3 разные категории (параметр, значение, описание). Нравится [time_specified_flag, 1, presence of the pts_time field]
Обновлено: это исходный дамп json в виде строки: "dump" : "======================================================================================================================================\r\n| PID: 0401 [SEC -> SCTE-35] length: 60[0x003C] status: VALID |\r\n--------------------------------------------------------------------------------------------------------------------------------------\r\nAddress Parameter Length Value Description\r\n--------------------------------------------------------------------------------------------------------------------------------------\r\n<span class=\"hex_tree_child\">0x0000,0: [-] PID: 0401 [SEC -> SCTE-35] <0x2A,0> : (37 nodes in 3 levels)</span>\r\n0x0000,0: * table_id <0x1,0> : 0xFC (252) SCTE 35\r\n0x0001,0: * section_syntax_indicator <0x0,1> : '0'\r\n0x0001,1: * private_indicator <0x0,1> : '0'\r\n0x0001,2: * reserved <0x0,2> : '11'\r\n0x0001,4: * section_length <0x1,4> : 0x39 (57)\r\n0x0003,0: * protocol_version <0x1,0> : 0\r\n0x0004,0: * encrypted_packet <0x0,1> : 0 no part of this message is encrypted\r\n0x0004,1: * encryption_algorithm <0x0,6> : 0 No encryption\r\n0x0004,7: * pts_adjustment <0x4,1> : 0xFFFF7F18 (-33000) => Time: 95443.4 sec => (hh:mm:ss.ms) 26:30:43.351\r\n0x0009,0: * cw_index <0x1,0> : 0x00 (0)\r\n0x000A,0: * tier <0x1,4> : 0x0FFF (4095)\r\n0x000B,4: * splice_command_length <0x1,4> : 0x0005 (5)\r\n0x000D,0: * splice_command_type <0x1,0> : 0x06 (6) time_signal\r\n<span class=\"hex_tree_child\">0x000E,0: [-] time_signal <0x5,0> : => Time: 19345 sec => (hh:mm:ss.ms) 05:22:24.972</span>\r\n0x000E,0: * time_specified_flag <0x0,1> : 1 presence of the pts_time field\r\n0x000E,1: * reserved <0x0,6> : 0x3F (63)\r\n0x000E,7: * pts_time <0x4,1> : PTS: 1741047514 [0x67C646DA] => Time: 19345 sec => (hh:mm:ss.ms) 05:22:24.972\r\n0x0013,0: * descriptor_loop_length <0x2,0> : 35\r\n<span class=\"hex_tree_child\">0x0015,0: [-] Descriptors <0x11,0> :</span>\r\n<span class=\"hex_tree_child\">0x0015,0: [-] segmentation_descriptor (0x02) <0x11,0> : Content Identification (0x01)</span>\r\n0x0015,0: * descriptor_tag <0x1,0> : 0x02 (2)\r\n0x0016,0: * descriptor_length <0x1,0> : 0x21 (33)\r\n0x0017,0: * identifier <0x4,0> : 0x43554549 (CUEI)\r\n0x001B,0: * segmentation_event_id <0x4,0> : 0x00000001 (1)\r\n0x001F,0: * segmentation_event_cancel_indicator <0x0,1> : '0' a previously sent segmentation event, identified by segmentation_event_id, has NOT been cancelled\r\n0x001F,1: * reserved <0x0,7> : 0x7F (127)\r\n0x0020,0: * program_segmentation_flag <0x0,1> : '1' the message refers to a Program Segmentation Point and that the mode is the Program Segmentation Mode whereby all PIDs/components of the program are to be segmented\r\n0x0020,1: * segmentation_duration_flag <0x0,1> : '0' No presence of segmentation_duration field\r\n0x0020,2: * delivery_not_restricted_flag <0x0,1> : '1' the next five bits are reserved\r\n0x0020,3: * reserved <0x0,5> : 0x1F (31)\r\n0x0021,0: * segmentation_upid_type <0x1,0> : 0x01 (1) Deprecated: use type 0x0C; The segmentation_upid does not follow a standard naming scheme.\r\n0x0022,0: * segmentation_upid_length <0x1,0> : 0x12 (18)\r\n0x0035,0: * segmentation_type_id <0x1,0> : 0x01 (1) Content Identification\r\n0x0036,0: * segment_num <0x1,0> : 0x01 (1)\r\n0x0037,0: * segments_expected <0x1,0> : 0x01 (1)\r\n0x0038,0: * CRC_32 <0x4,0> : 0x46D15AF3 CRC OK\r\n======================================================================================================================================\r\n",
Вот мой фрагмент кода для форматирования этого блока данных:
Мой код для форматирования ответа JSON
Это то, что возможно сделать?
Все возможно, если приложить некоторые усилия. Не могли бы вы поделиться кодом, который вы пробовали, или местом, где вы застряли.
Функция map легко справится с этим. Кроме того, может быть проще работать с оригинальной структурой json. На что это похоже?
@maazadeeb Я обновил пост.
Кроме того, @ToddSkelton на JSON больно смотреть. Поэтому мне нужно было отформатировать меня, чтобы брать только важные вещи.
Попался, я не понял, что это была просто одна большая строка.
Как вам нужны те, у которых нет просто числового формата? Например, каков ожидаемый результат для 'pts_time: PTS: 1741047514 [0x67C646DA] > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972'
@ToddSkelton, это интересно. pts_time будет параметром, PTS: 1741047514 [0x67C646DA] будет значением, а > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972 будет описанием.
@TayshawnHill ... было ли этого уже достаточно?... версия 1 точно соответствует/захватывает pts_time подобные форматы/категории, тогда как версия 2 соответствует/захватывает более общие форматы/категории.
@PeterSeliger версии 2 группирует их так, как мне бы хотелось. Однако я не уверен, как использовать регулярное выражение для помещения параметра, значения и описания в объект.
@TayshawnHill ... было ли этого уже достаточно?... версия 1 точно соответствует/захватывает pts_time подобные форматы/категории, тогда как версия 2 соответствует/захватывает более общие форматы/категории. — Петр Селигер
@PeterSeliger версии 2 группирует их так, как мне бы хотелось. Однако я не уверен, как использовать регулярное выражение для помещения параметра, значения и описания в объект. - Тайшон Хилл
... вот так ...
function createKeyValueAndDescriptionList(pattern) {
const regXCompositeValue = (/^(?<key>[^:]+)\:\s*(?:(?<value>[A-Za-z]+\:\s*[^>]+))\s*(?<description>.*)/);
const regXGenericValue = (/^(?<key>[^:]+):\s*(?<value>[\w']+(?:\s*\([^)]*\))*)\s*(?<description>.*)/);
const { groups } = (
regXCompositeValue.exec(pattern) ||
regXGenericValue.exec(pattern) ||
{}
);
return (groups && [
groups.key,
groups.value.trim(),
groups.description || '',
] || []);
}
console.info([
'table_id: 0xFC (252) SCTE 35',
"section_syntax_indicator: '0'",
"private_indicator: '0'",
"reserved: '11'",
'section_length: 0x39 (57)',
'protocol_version: 0',
'encrypted_packet: 0 no part of this message is encrypted',
'encryption_algorithm: 0 No encryption',
'pts_adjustment: 0xFFFF7F18 (33000) > Time: 95443.4 sec > (hh:mm:ss.ms) 26:30:43.351',
'cw_index: 0x00 (0)',
'tier: 0x0FFF (4095)',
'splice_command_length: 0x0005 (5)',
'splice_command_type: 0x06 (6) time_signal [] time_signal: > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'time_specified_flag: 1 presence of the pts_time field',
'reserved: 0x3F (63)',
'pts_time: PTS: 1741047514 [0x67C646DA] > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'descriptor_loop_length: 35 [] Descriptors: [] segmentation_descriptor (0x02): Content Identification (0x01)',
'descriptor_tag: 0x02 (2)',
'descriptor_length: 0x21 (33)',
'identifier: 0x43554549 (CUEI)',
'segmentation_event_id: 0x00000001 (1)',
"segmentation_event_cancel_indicator: '0' a previously sent segmentation event, identified by segmentation_event_id, has NOT been cancelled",
'reserved: 0x7F (127)',
"program_segmentation_flag: '1' the message refers to a Program Segmentation Point and that the mode is the Program Segmentation Mode whereby all PIDs/components of the program are to be segmented",
"segmentation_duration_flag: '0' No presence of segmentation_duration field",
"delivery_not_restricted_flag: '1' the next five bits are reserved",
'reserved: 0x1F (31)',
'segmentation_upid_type: 0x01 (1) Deprecated: use type 0x0C; The segmentation_upid does not follow a standard naming scheme.',
'segmentation_upid_length: 0x12 (18)',
'segmentation_type_id: 0x01 (1) Content Identification',
'segment_num: 0x01 (1)',
'segments_expected: 0x01 (1)',
'CRC_32: 0x46D15AF3 CRC OK',
].map(createKeyValueAndDescriptionList));
console.info([
"foo:------------",
"bar:++++++++++++",
"baz:############",
].map(createKeyValueAndDescriptionList));
.as-console-wrapper { min-height: 100%!important; top: 0; }
@TayshawnHill ... Я предоставил отсутствующую обработку сбоев. Метод молча завершается сбоем, возвращая пустой массив для каждого шаблона, который не может быть сопоставлен.
function threeSplit(line){
sep1= line.indexOf(": ")
a = line.slice(0,sep1)
line =line.slice(sep1+2)
sep2 = line.indexOf(" ")
b = line.slice(0,sep2)
c=line.slice(sep2+1)
return [a,b,c]
}
[
'table_id: 0xFC (252) SCTE 35',
"section_syntax_indicator: '0'",
"private_indicator: '0'",
"reserved: '11'",
'section_length: 0x39 (57)',
'protocol_version: 0',
'encrypted_packet: 0 no part of this message is encrypted',
'encryption_algorithm: 0 No encryption',
'pts_adjustment: 0xFFFF7F18 (33000) > Time: 95443.4 sec > (hh:mm:ss.ms) 26:30:43.351',
'cw_index: 0x00 (0)',
'tier: 0x0FFF (4095)',
'splice_command_length: 0x0005 (5)',
'splice_command_type: 0x06 (6) time_signal [] time_signal: > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'time_specified_flag: 1 presence of the pts_time field',
'reserved: 0x3F (63)',
'pts_time: PTS: 1741047514 [0x67C646DA] > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972',
'descriptor_loop_length: 35 [] Descriptors: [] segmentation_descriptor (0x02): Content Identification (0x01)',
'descriptor_tag: 0x02 (2)',
'descriptor_length: 0x21 (33)',
'identifier: 0x43554549 (CUEI)',
'segmentation_event_id: 0x00000001 (1)',
"segmentation_event_cancel_indicator: '0' a previously sent segmentation event, identified by segmentation_event_id, has NOT been cancelled",
'reserved: 0x7F (127)',
"program_segmentation_flag: '1' the message refers to a Program Segmentation Point and that the mode is the Program Segmentation Mode whereby all PIDs/components of the program are to be segmented",
"segmentation_duration_flag: '0' No presence of segmentation_duration field",
"delivery_not_restricted_flag: '1' the next five bits are reserved",
'reserved: 0x1F (31)',
'segmentation_upid_type: 0x01 (1) Deprecated: use type 0x0C; The segmentation_upid does not follow a standard naming scheme.',
'segmentation_upid_length: 0x12 (18)',
'segmentation_type_id: 0x01 (1) Content Identification',
'segment_num: 0x01 (1)',
'segments_expected: 0x01 (1)',
'CRC_32: 0x46D15AF3 CRC OK'].map(threeSplit)
[
[ 'table_id', '0xFC', '(252) SCTE 35' ],
[ 'section_syntax_indicator', "'0", "'0'" ],
[ 'private_indicator', "'0", "'0'" ],
[ 'reserved', "'11", "'11'" ],
[ 'section_length', '0x39', '(57)' ],
[ 'protocol_version', '', '0' ],
[ 'encrypted_packet', '0', 'no part of this message is encrypted' ],
[ 'encryption_algorithm', '0', 'No encryption' ],
[
'pts_adjustment',
'0xFFFF7F18',
'(33000) > Time: 95443.4 sec > (hh:mm:ss.ms) 26:30:43.351'
],
[ 'cw_index', '0x00', '(0)' ],
[ 'tier', '0x0FFF', '(4095)' ],
[ 'splice_command_length', '0x0005', '(5)' ],
[
'splice_command_type',
'0x06',
'(6) time_signal [] time_signal: > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972'
],
[ 'time_specified_flag', '1', 'presence of the pts_time field' ],
[ 'reserved', '0x3F', '(63)' ],
[
'pts_time',
'PTS:',
'1741047514 [0x67C646DA] > Time: 19345 sec > (hh:mm:ss.ms) 05:22:24.972'
],
[
'descriptor_loop_length',
'35',
'[] Descriptors: [] segmentation_descriptor (0x02): Content Identification (0x01)'
],
[ 'descriptor_tag', '0x02', '(2)' ],
[ 'descriptor_length', '0x21', '(33)' ],
[ 'identifier', '0x43554549', '(CUEI)' ],
[ 'segmentation_event_id', '0x00000001', '(1)' ],
[
'segmentation_event_cancel_indicator',
"'0'",
'a previously sent segmentation event, identified by segmentation_event_id, has NOT been cancelled'
],
[ 'reserved', '0x7F', '(127)' ],
[
'program_segmentation_flag',
"'1'",
'the message refers to a Program Segmentation Point and that the mode is the Program Segmentation Mode whereby all PIDs/components of the program are to be segmented'
],
[
'segmentation_duration_flag',
"'0'",
'No presence of segmentation_duration field'
],
[
'delivery_not_restricted_flag',
"'1'",
'the next five bits are reserved'
],
[ 'reserved', '0x1F', '(31)' ],
[
'segmentation_upid_type',
'0x01',
'(1) Deprecated: use type 0x0C; The segmentation_upid does not follow a standard naming scheme.'
],
[ 'segmentation_upid_length', '0x12', '(18)' ],
[ 'segmentation_type_id', '0x01', '(1) Content Identification' ],
[ 'segment_num', '0x01', '(1)' ],
[ 'segments_expected', '0x01', '(1)' ],
[ 'CRC_32', '0x46D15AF3', 'CRC OK' ]
]
`
Можете ли вы поделиться небольшим фрагментом JSON из URL-адреса, а также кодом, который вы использовали для его форматирования в эту структуру?