2016-08-22 2 views
-1
$text = <<"EOF"; 
{"product_id": "5I20SL43MWDD", "title": "Woodland Imports 2 Piece Ceramic Vase Set", "primary_shelf": [{"all_paths_str": "[[\"Home Page\",\"Home\",\"Decor\",\"Vases\"]]", "locale": "en_US", "value": "Vases", "path_id": "[\"0\",\"4044\",\"133012\",\"1043827\"]", "all_paths_id": "[[\"0\",\"4044\",\"133012\",\"1043827\"]]", "tag_source": "rule", "id": "1043827", "path_str": "[\"Home Page\",\"Home\",\"Decor\",\"Vases\"]"}], "alternate_shelves": "1043827", "last_updated_at": 1471417348, "primary_category_path": "0:4044:133012:1043827", "short_description": "Includes two vase. Gray and cream color palette. No assembly required. 5 in. L x 5 in. W x 12 in. H. Weight: 6 lbs.. Check out this Vase that will beautify your interiors. Can be kept assorted or separately depending upon your needs. For added beauty, you can also add flowers to this ceramic vase to flourish your interiors with fragrance. This vase will steal the spotlight and make you win appreciations from many. Besides, this vase can also be gifted to your beloved ones.", "item_id": "40966792", "attributes": {"package_quantity": ["1"], "assembled_product_width_raw_data": ["6.0"], "assembled_product_length_raw_data": ["6.0"], "is_always_show": ["N"], "assembled_product_height_raw_data": ["15.0", "15.0"], "color": ["Brown", "Brown"], "small_parts_warning_code": ["0"], "manufacturer_part_number": ["78681"], "primary_shelf_id": ["1043827"], "shape": ["Bud"], "manufacturer_suggested_retail_price": ["75.84"], "country_of_origin_components": ["Imported"], "assembled_product_length": ["6.0 IN", "6.0"], "category": ["Vases", "Vases"], "has_warranty": ["N"], "character_primary_category_path": ["Home/Decor/Vases"], "item_master_created_date": ["1414926519000"], "offer_lifecycle_status": ["ACTIVE"], "new": ["N"], "size": ["12\" H x 5\" W x 5\" D", "12\" H x 5\" W x 5\" D"], "type": ["Other Vases"], "brand": ["Woodland Imports", "Woodland Imports"], "all_shelves": ["Vases"], "is_preorder": ["N"], "primary_shelf": ["Vases"], "material": ["Ceramic", "Ceramic"], "assembled_product_width": ["6.0 IN", "6.0"], "california_residents_prop_65_warning_required": ["N"], "lifestage": ["Adult", "Adult"], "show_button_in": ["3"], "warranty_information": ["Warranty not available for this item"], "char_primary_category_path": ["Home/Decor/Vases"], "manufacturer": ["Woodland Imports"], "actual_color": ["Brown", "Brown"], "data_source": ["Catalog"], "product_type": ["Vases"], "size_raw_data": ["12"], "wupc": ["0083730378681"], "display_status": ["PUBLISHED"], "assembled_product_weight": ["7 Pounds"], "country_of_origin_assembly": ["Imported"], "assembled_product_height": ["15.0 IN", "15.0"], "warranty_length": ["Warranty not available for this item"], "model": ["78681"], "price_per_unit_quantity": ["1"]}, "long_description": "WLI15311<br /><strong>Features</strong><br /><li>Grey and cream color palette</li><li>Made of quality ceramic</li><li>Product Type: Floor vase</li><li>Shape: Bud</li><li>Color: Grey and cream</li><li>Primary Material: Ceramic</li> <br /><strong>Dimensions</strong><br />Size 15'' H x 6'' W x 6'' D<br /><li>Overall Height - Top to Bottom: 15''</li><li>Overall Width - Side to Side: 6''</li><li>Overall Depth - Front to Back: 6''</li><li>Overall Product Weight: 5.93 lbs</li><br />Size 12'' H x 5'' W x 5'' D<br /><li>Overall Height - Top to Bottom: 12''</li><li>Overall Width - Side to Side: 5''</li><li>Overall Depth - Front to Back: 5''</li><li>Overall Product Weight: 3.24 lbs</li>"} 
EOF 

Это мой текст, который находится в формате json. Я хочу, чтобы извлечь определенные поля, такие как short_description и long_descriptionPerl Regular Expression не работает для long_description

Я использую это регулярное выражение:

my ($title)=$text=~/"title"\s*:\s*"(.*?)"\s*,\s*"/is;** 
my ($long_des)=$text=~/"long_description"\s*:\s*"(.*?)"\s*,\s*"/is; 

Все идет правильно, но я не знаю, почему long_description регулярное выражение не работает, я получаю пустой строка. Что мне нужно сделать, чтобы исправить это?

+5

Если вы разбора JSON, почему бы не использовать 'JSON' и спасти себя от хлопот? –

+0

Я не знаю, почему этот народ опрокидывает вопрос. Я не знаю лучше, чем только задал вопрос. Thnx для ответа и показа мне лучший способ сделать это. –

ответ

5

Я предлагаю сделать шаг назад. Это неприятно взломать JSON с регулярным выражением из-за контекстуального характера JSON. Regex не является контекстуальным, поэтому всегда является хакерским решением.

К счастью, Perl имеет JSON модуль, который делает его простым:

#!/usr/bin/env perl 

use strict; 
use warnings; 
use Data::Dumper; 
use JSON; 

my $json_str = q({"product_id": "5I20SL43MWDD", "title": "Woodland Imports 2 Piece Ceramic Vase Set", "primary_shelf": [{"all_paths_str": "[[\"Home Page\",\"Home\",\"Decor\",\"Vases\"]]", "locale": "en_US", "value": "Vases", "path_id": "[\"0\",\"4044\",\"133012\",\"1043827\"]", "all_paths_id": "[[\"0\",\"4044\",\"133012\",\"1043827\"]]", "tag_source": "rule", "id": "1043827", "path_str": "[\"Home Page\",\"Home\",\"Decor\",\"Vases\"]"}], "alternate_shelves": "1043827", "last_updated_at": 1471417348, "primary_category_path": "0:4044:133012:1043827", "short_description": "Includes two vase. Gray and cream color palette. No assembly required. 5 in. L x 5 in. W x 12 in. H. Weight: 6 lbs.. Check out this Vase that will beautify your interiors. Can be kept assorted or separately depending upon your needs. For added beauty, you can also add flowers to this ceramic vase to flourish your interiors with fragrance. This vase will steal the spotlight and make you win appreciations from many. Besides, this vase can also be gifted to your beloved ones.", "item_id": "40966792", "attributes": {"package_quantity": ["1"], "assembled_product_width_raw_data": ["6.0"], "assembled_product_length_raw_data": ["6.0"], "is_always_show": ["N"], "assembled_product_height_raw_data": ["15.0", "15.0"], "color": ["Brown", "Brown"], "small_parts_warning_code": ["0"], "manufacturer_part_number": ["78681"], "primary_shelf_id": ["1043827"], "shape": ["Bud"], "manufacturer_suggested_retail_price": ["75.84"], "country_of_origin_components": ["Imported"], "assembled_product_length": ["6.0 IN", "6.0"], "category": ["Vases", "Vases"], "has_warranty": ["N"], "character_primary_category_path": ["Home/Decor/Vases"], "item_master_created_date": ["1414926519000"], "offer_lifecycle_status": ["ACTIVE"], "new": ["N"], "size": ["12\" H x 5\" W x 5\" D", "12\" H x 5\" W x 5\" D"], "type": ["Other Vases"], "brand": ["Woodland Imports", "Woodland Imports"], "all_shelves": ["Vases"], "is_preorder": ["N"], "primary_shelf": ["Vases"], "material": ["Ceramic", "Ceramic"], "assembled_product_width": ["6.0 IN", "6.0"], "california_residents_prop_65_warning_required": ["N"], "lifestage": ["Adult", "Adult"], "show_button_in": ["3"], "warranty_information": ["Warranty not available for this item"], "char_primary_category_path": ["Home/Decor/Vases"], "manufacturer": ["Woodland Imports"], "actual_color": ["Brown", "Brown"], "data_source": ["Catalog"], "product_type": ["Vases"], "size_raw_data": ["12"], "wupc": ["0083730378681"], "display_status": ["PUBLISHED"], "assembled_product_weight": ["7 Pounds"], "country_of_origin_assembly": ["Imported"], "assembled_product_height": ["15.0 IN", "15.0"], "warranty_length": ["Warranty not available for this item"], "model": ["78681"], "price_per_unit_quantity": ["1"]}, "long_description": "WLI15311<br /><strong>Features</strong><br /><li>Grey and cream color palette</li><li>Made of quality ceramic</li><li>Product Type: Floor vase</li><li>Shape: Bud</li><li>Color: Grey and cream</li><li>Primary Material: Ceramic</li> <br /><strong>Dimensions</strong><br />Size 15'' H x 6'' W x 6'' D<br /><li>Overall Height - Top to Bottom: 15''</li><li>Overall Width - Side to Side: 6''</li><li>Overall Depth - Front to Back: 6''</li><li>Overall Product Weight: 5.93 lbs</li><br />Size 12'' H x 5'' W x 5'' D<br /><li>Overall Height - Top to Bottom: 12''</li><li>Overall Width - Side to Side: 5''</li><li>Overall Depth - Front to Back: 5''</li><li>Overall Product Weight: 3.24 lbs</li>"}); 
my $json = from_json($json_str); 

print Dumper $json; 

print "LONG:", $json ->{long_description},"\n"; 
+0

Buddy Я хочу использовать его так: my $ json_str = q ($ text); это не работает. Я использую ваше решение только –

+0

Это не так. 'q()' фактически представляет собой одиночную кавычку (которую я использую из-за кавычек в строке). Поэтому он пытается буквально разгласить '' $ text''. Просто используйте 'my $ json = from_json ($ text);' если он уже находится в переменной. – Sobrique

Смежные вопросы