-1

Hello I have the following multiline text:

data="""

var config = {
                locale: 'es',
                userAuthenticated: false,
                propertyId: 94616716,
                favoriteFirstTime: true,
                discardFirstTime: true,
                urlAddFavorite: '/add-favorite.htm',
                urlAdNewContactInfo: '/es/ajax/listingController/adContactInfoForDetail.ajax',
                addFavoriteTargetId: '32',
                discardTargetId: '39',
                viewStatisticsTargetId: '40',
                urlRemoveFavorite: '/remove-favorite.htm',
                urlAddDiscarded: '/add-ruled-out-detail.htm',
                urlRemoveDiscarded: '/remove-ruled-out.htm',
                urlAddComment: '/update-favorite-comment.htm',
                urlContact: '/ajax/contact/2/sendcontact.ajax',
                urlCounterOffer: '/ajax/contact/suggested/4/sendcontact.ajax',
                urlContactDetailGallery: '/ajax/contact/42/sendcontact.ajax',
                urlContactDetailGalleryVirtualTour: '/ajax/contact/suggested/sendcontact.ajax',
                urlContactDetailGalleryFloorPlan: '/ajax/contact/45/sendcontact.ajax',
                urlContactDetailGallery3DTour: '/ajax/contact/46/sendcontact.ajax',
                urlContactDetailGalleryVideo: '/ajax/contact/47/sendcontact.ajax',
                urlContactVideoVisitation : '/ajax/contact/sendVideoVisitationContact.ajax',
                urlSuggestedAgencies: '/ajax/zoneexperts/suggested/2/sendcontact.ajax',
                urlReloadCaptcha: '/ajax/captcha/reloadCaptcha.ajax',
                urlVirtualTour: '',
                urlAlertSummary: '/ajax/alertsummary.ajax/25',
                mediaTablet: 'screen and (max-device-width: 1023px) and (min-device-width: 767px), screen and (max-width: 1023px) and (min-width: 767px)',
                mediaMobile: 'screen and (max-width: 767px)',
                mediaDesktop: 'screen and (min-width: 1024px) and (min-device-width: 1024px)',
                mediaLandscape: 'screen and (orientation: landscape)',
                mortgagesMinSavingsToContact: 7,
                showLightboxPosition: null,
                showLightboxVirtualTour: false,
                detailUrl: '/inmueble/94616716/',
                imageSizes: {"1280X400":80,"140X105":80, "140":80, "300":85, "600":80, "850":80, "1500":80, "250X188":80, "500X375":80, "300X225":80, "600X450":80},
                maxAdContactMessagesSuggested: 3,
                openContactModal: false,
                showAdIncidenceForm: false,
                urlContactMortgages: '/ajax/contact-mortgages.ajax?xtatc=[detalle_solicitar_hipoteca]',
                xitiClientMarkup: {detailFavoritesLoginInPlace:"detalle::conversiones::login-favoritear-inplace",detailRuledOutLoginInPlace:"detalle::conversiones::login-descartar-inplace",detailIncidenceSendForm:"detalle::conversiones::form-reportar-error",detailContactForm:"detalle::conversiones::form_contacto"},
                contactInGalleryLightboxTitle: "Contactar",
                contactInGalleryFormTitle: "¿Te ha gustado?",
                urlCreateUserAskingStats: '/new-user-asking-stats.ajax',
                showMorePhotos: {
                    desktop: {
                        position: 4,
                        threshold: 4,
                    },
                    mobile: {
                        position: 3,
                        threshold: 3,
                    }
                },
                phoneIntlConfig: {
                    initialCountry : "es",
                    preferredCountries : [],
                    allCountries: []
                },
                urlCalculateUCISavings: '/ajax/calculate-savings-form',
                urlConversations: '',
                currentSearchUrl: '/alquiler-habitacion/barcelona-provincia/?ordenado-por=fecha-publicacion-desc&ordenado-por=fecha-publicacion-desc',
                urlResultsFromComparator: '/ajax/retrieve-comparator-results.ajax',
                urlResultsFromValidationStep1: '/hipotecas/validate-mortgages-contact-step1.ajax',
                urlResultsFromValidationStep2: '/hipotecas/validate-mortgages-contact-step2.ajax',
                staticsBaseUri: 'https://st1.idealista.com/static',
                galleryReactToggle: true,
                isFavourite: false,
                showContact: true,
                detailWithSuggestionsToggle: true,
                hasToShowRecommendations: false,
                auctionDepositTooltipTitle: "¿Cómo se calcula el depósito?",
                auctionDepositTooltipBody: "Se calcula a partir de la oferta que se quiere presentar o al precio de venta de base, según la subasta.",
                useMaxImageSizeDesktop850: true,
                useFixedHeightFakeAnchors: true,
                useBufferGalleryAdapted: true,
                showActionsRecommendationsDetail: false,
                detailWithSuggestionsGalleryToggle: false,
            };
            var microsoft_key = '';
            var mapConfig = {
                latitude: '41.4104573',
                longitude: '2.1971312',
                onMapElements: false,
                markerType: 0,
                markerVisible: 1,
                i18nDetail: '',
                versionId: '3.30',
                language: 'es',
                clientId: 'gme-idealistalibertad1',
                dataProvider: 'googlev3',
                channel: 'map_detail'
            };
"""

I am looking for a way to convert that text (JS OBJECT) to a JSONF file or a python dic.

I just need a way to get the "latitude" and "longitude" value that are in "var map Config"

var mapConfig = {
                latitude: '41.4104573',
                longitude: '2.1971312',
                onMapElements: false,
                markerType: 0,
                markerVisible: 1,
                i18nDetail: '',
                versionId: '3.30',
                language: 'es',
                clientId: 'gme-idealistalibertad1',
                dataProvider: 'googlev3',
                channel: 'map_detail'
            };

I know that I can use regex multiline too, but, I´m looking for the best and easy way to get it.

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
  • What have you tried to come up with such a regex? Please share your code, what you got and what you expected. https://stackoverflow.com/help/how-to-ask – Grismar Jul 01 '21 at 03:35
  • A regex is generally the wrong tool for the job. HTML is not a regular language; regular expressions are categorically incapable of parsing it. JavaScript, likewise. – Charles Duffy Jul 01 '21 at 03:40

1 Answers1

1
  • Extract mapConfig from data
    import re
    map_config_str = re.search('mapConfig = ([^;]*);', data).group(1) 
    
  • Decode the javascript object from string into a python dict using demjson or other libraries
    import demjson
    map_config = demjson.decode(map_config_str)
    print(map_config['latitude'], map_config['longitude'])
    
Zebartin
  • 124
  • 10