Parse a JSON body after multipart ajax Angular call

风格不统一 提交于 2019-12-13 09:01:17

问题


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?


回答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);



回答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 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;
};


来源:https://stackoverflow.com/questions/40587172/parse-a-json-body-after-multipart-ajax-angular-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!