我试图解析使用ajax angularJs在api调用后来找我的身体。 通话后,回复是:
--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--
我没有找到一个插件来获取此请求的正文。我是否需要制作手动解析器或者我可以获得另一种解决方案。 有人能帮我吗?
答案 0 :(得分:0)
您可以在每个参数中使用String.prototype.slice()
String.prototype.indexOf()
来获取"{"
,"}"
,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);

答案 1 :(得分:0)
这是我解析API调用之后的任何表单数据的解决方案:
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;
};