Search code examples
javascriptarraysjsonregexresponse

Regex values in JSON response


I want to regex JSON response value in AJAX without losing the structure of JSON. Here is the ajax

$.ajax({
    url: "date.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    dataType: "json",
    headers: {
        "X-Requested-With": "XMLHttpRequest",
    },
    success: function(data) {
        var formDatax = new FormData();
        var date = data.results;
        var res = date.map(function(item) {
            return { 
            "images": item.images
            };
        });

        $.ajax({
            url: "json.php",
            type: "POST",
            data: JSON.stringify(res),
            processData: false,
            contentType: false,
            dataType: "json",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
            },
            success: function(data) {

            },
            error: function() {}
        });
    },
    error: function() {}
});

Here is an example of JSON Response

{  
      "part_number_key":"DDASDAS",
      "name":"ASD",
      "description":"asd",
      "price":12,
      "general_stock":12,
      "brand":"ASD",
      "category_id":2776,
      "images":[  
         {  
            "url":"https://asd.com/asd/asd/1241.jpg",
            "display_type":1
         },
         {  
            "url":"https://asd.com/asd/asd/73223.jpg",
            "display_type":0
         },
         {  
            "url":"https://asd.com/asd/asd/214121.jpg",
            "display_type":0
         }
      ],
      "warranty":24
   },

I want to get the link of the image where the display_type is having value 1, so I thought it's ok if I regex the first url before "display_type":1 but I'm not able because this is not string to regex.

/(https?\:\/\/[^\" ][^]).*("display_type":1)/i

The regex, it's not complete because I saw the problem about the string I didn't tried to complete the regex...


Solution

  • You could parse the JSON and use filter and map to get the images URL

    success: function(data) {
       var response = JSON.parse(data)
       var imagesURL = response.images.filter(image => image.display_type).map(image => image.url)
    }