Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...