Skip to content Skip to sidebar Skip to footer

Parse A Json Body After Multipart Ajax Angular Call

I'm trying to parse a body that is coming to me after an api call using ajax angularJs. After call the response is: --3531b7e68196e3144197f82db0864b7e391c8b0ad51c4176c28f8ac41b3c C

Solution 1:

You can use String.prototype.slice() with String.prototype.indexOf() at each parameter to get indexes of "{", "}", JSON.parse().

let response = `--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 json = JSON.parse(response.slice(response.indexOf("{")
           , response.indexOf("}") + 1));

let {name} = json;

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

Solution 2:

This is my solution for parsing any form data that is coming after an API call:

parser = function (data) {
  // this will split --1491test9246asaery134214// if you have multiple files in the responsevar dataArray = data.split(/--\S*[0-9a-z]/g), response = {};
  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, '');
      response[name] = body;
    }
  });
  return response;
};

Post a Comment for "Parse A Json Body After Multipart Ajax Angular Call"