-1

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
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--

I didn't find a plugin to get the body from this request. Do I need to make manual parser or I could get another solution. Can someone help me?

Vlad
  • 9
  • 1
  • What is expected result? – guest271314 Nov 14 '16 at 11:18
  • See [`FormData`](https://xhr.spec.whatwg.org/#interface-formdata) – guest271314 Nov 14 '16 at 11:25
  • my expected result is the json { "name": "Nothing", "dob_display": "10/11/1997", "dob_accuracy": "FD", "owner_firstname": "Nothing", "owner_surname": "To Understand" } and after that to have access like an object in angular. – Vlad Nov 14 '16 at 11:33
  • Not sure how you receiving the raw `FormData` as a string? Can you include `javascript` at Question which returns the string? – guest271314 Nov 14 '16 at 16:46
  • I'm making a call using ajax.post to server and the response is coming like I wrote this is it :( And I need the object from that response. { "name": "Nothing" ..... } – Vlad Nov 15 '16 at 10:41

2 Answers2

0

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);
guest271314
  • 1
  • 15
  • 104
  • 177
0

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 response
  var 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;
};
Vlad
  • 9
  • 1