A client wants to be able to make xmlhttp ajax requests with the default content type of content-type:"application/x-www-form-urlencoded; charset=UTF-8" but sending the data in the form the API expects application/json. So the request comes across as this:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"processData": false,
"data": "{\n\t\"practice\": [\"Learning\"]\n}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
But the API expects to be able to get req.body as a JSON object it can immediately use:
"{"practice":["Learning"]}"
Can I transform this "{\n\t\"practice\": [\"Learning\"]\n}" to this "{"practice":["Learning"]}" in some safe/suggested manner? (without some home grown parsing function or regex)
Yes, the JSON.parse
function can be used for this:
try{JSON.stringify(JSON.parse(data))}
will convert strange json with newlines to standard one line string json.
JSON.parse
Parses the json into an object
JSON.stringify
Turns an object into a one line formatted JSON object
try
JSON.parse will fail if an invalid json string is passed. (\ns are valid in json.parse)
If this you meant converting "{\n\"your\":\n \"object\"}"
to a javascript object like {"your": "object"}
, you can just use try{JSON.parse(variablename)}
According to these answers, for older browsers you may need JSON-js
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments