Decipher a JSON payload following a multipart AJAX request in Angular

My current task involves parsing the body of a response I receive after making an API call using Ajax in AngularJS. The response looks like this:

--3531b7e68196e3144197f82db0864b7e391c8b0ad51c4176c28f8ac41b3c
Content-Disposition: form-data; name="passport"; filename="passport.json"
Content-Type: application/json

{
    "name": "Nothing",
    "dob_display": "10/11/1997",
    "dob_accuracy": "FD",
    "owner_firstname": "Nothing",
    "owner_surname": "To Understand"
}
--3531b7e68196e3144197f82db0864b7e391c8b0ad51c4176c28f8ac41b3c--

Unfortunately, I haven't been able to find a plugin that can extract the body from this type of request. Should I create a manual parser or is there another solution available? I would greatly appreciate any assistance.

Answer №1

To extract the indexes of "{" and "}" along with parsing JSON, you can utilize String.prototype.slice() in conjunction with String.prototype.indexOf().

let data = `--3531b7e68196e3144197f82db0864b7e391c8b0ad51c4176c28f8ac41b3c
Content-Disposition: form-data; name="passport"; filename="passport.json"
Content-Type: application/json

{
    "name": "Nothing",
    "dob_display": "10/11/1997",
    "dob_accuracy": "FD",
    "owner_firstname": "Nothing",
    "owner_surname": "To Understand"
}
--3531b7e68196e3144197f82db0864b7e391c8b0ad51c4176c28f8ac41b3c--`;

let jsonData = JSON.parse(data.slice(data.indexOf("{")
           , data.indexOf("}") + 1));

let {name} = jsonData;

console.log(jsonData);
console.log({name});
console.log(name);

Answer №2

Here's a handy function I created to efficiently parse form data received after an API request:

formDataParser = function (data) {
  // Splitting based on pattern --1491test9246asaery134214
  // Handling multiple files in the response
  var dataArray = data.split(/--\S*[0-9a-z]/g), parsedData = {};
  underscore.each(dataArray, function (dataBlock) {
    var rows = dataBlock.split('\n'),
        header = rows.splice(0, 4).slice(1, 3),
        body = rows.join('');

    if (header.length > 1) {
      var patternGetName = /(".*?")/g,
          name = patternGetName.exec(header[0])[0].replace(/(")/g, '');
      parsedData[name] = body;
    }
  });
  return parsedData;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ajax causing issues with comments display on rails platform

Having trouble rendering comments using ajax in my rails app. The comments are only displayed after redirecting the page, even though they are successfully created. The issue seems to be with rendering comments using ajax and jquery! In my application.htm ...

What is the process of creating a MaterialUI checkbox named "Badge"?

Badge API at https://material-ui.com/api/badge/ includes a prop called component that accepts either a string for a DOM element or a component. In my code: <Badge color="primary" classes={{ badge: classes.badge }} component="checkbox"> <Avatar ...

Utilizing Ramda JS for multi-dimensional grouping

I've been attempting to group the object by tag, folder, and report keys using GroupBy at multiple levels. While I was successful in grouping at a single level, I encountered difficulty in progressing further. const data = [{ "_index": "search_in ...

Implementing new records in Laravel's result collection

I am currently working on a function to retrieve all maximum offers from the maxoffers table: public function maxoffers($id) { $offers = Maxoffer::where('article_id', $id)->latest()->get(['id', 'price', 'st ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

Implementing X.PagedList within a modal pop-up window

I have implemented a modal pop-up on a webpage: ... <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="companySearchModal" aria-hidden="true" id="companySearchModal"> <div class="modal-dialog" role="document"> ...

The integration of a Bootstrap modal within the side bar's rendering

Struggling with a modal appearing inside my side div and can't find any solutions in the bootstrap5 documentation or online forums. https://i.stack.imgur.com/gHsBi.png I just want the modal to display centered on the page with the background fade ef ...

Issue involving JSON data submission using JQuery Ajax POST

Despite trying multiple variations of the AJAX Post request, I am still unable to receive the correct request in my Express app. var json = {} var skus = [1,2,3] json.data = { "test":"test", "aoeu":"aoeu" } $.post('/jet/api/putProduct', ...

Having issues with parsing JSON data from the Supreme website using Python

So here is the code I've been working on: import urllib.request, json with urllib.request.urlopen("https://www.supremenewyork.com/mobile_stock.json") as url: data = json.loads(url.read().decode()) print(type(data['Shoes'])) ...

Tips on saving HTML table information into a .txt document?

Welcome to my Unique HTML Table. <table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email Id</th> <th>Phone Number</th> <th>Prefered C ...

``There seems to be an issue with the code not iterating through the

$(function () { var data; $.getJSON("menu.json", function(data){ //console.log(data); //console.log(data.menu); //console.log(data.menu.length); //console.log(data.menu[1].link); //getMenuItem(data); var $menu = $("#menu"); ...

The getHours function seems to be malfunctioning when calculating the difference between dates

[code][1] Hello, I am currently working on calculating the difference between two dates and I want the result to be displayed in the format 00:00:00. Currently, my "current" time is set as 00:00:00 but I need it to dynamically update based on the hours, m ...

The slideUp function is not functioning as expected

I am trying to implement a slideUp effect on my webpage. Here is the code within my <body> tag: <script> $('#slide_up').click(function(){ $('p.text_study').slideUp('slow', function() { $ ...

Tips for preserving modifications made to a dictionary?

I have a JSON file that is dynamic and can be updated externally, but I also need to update it internally by loading it whenever access is needed (using @property). Furthermore, I need to ensure that any changes I make to the JSON file within my Python sc ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

HTML / CSS / JavaScript Integrated Development Environment with Real-time Preview Window

As I've been exploring different options, I've noticed a small but impactful nuance. When working with jQuery or other UI tools, I really enjoy being able to see my changes instantly. While Adobe Dreamweaver's live view port offers this func ...

"Enhance your JavaScript skills with the power of jQuery

I am currently facing an issue where I need to retrieve the value of the normaltagCmt element: <div id="random no"> <div id="normaltagdialog"> <table style="width:100%; height:100%" border="2px"> <tr style="width:100%; height: ...

Exploring the Process of Iterating Through a JSON Array in Angular

Within my angular application, I am utilizing an API to retrieve data regarding a chosen country. However, I am encountering difficulties in showcasing the "name" property from the languages section within the response data: [{ "name": "Colombia", ...

The AjaxPoller object is not defined and causing a TypeError

I have a piece of JavaScript code that handles AJAX requests and updates the DOM: this.AjaxHandler = { sendRequest: sendRequest, fetchDataForElement: fetchDataForElement, handleJsonResponse: handleJsonResponse, checkProgress: checkProgress }; fun ...

Issues with PHP server handling JSON files

I'm having some trouble retrieving server data to display in a table on my iPhone. The process involves the standard flow of server - php_interface - iOS. Initially, I attempted to use an echo json_encode(array) setup, but ran into issues with populat ...