lance-p
lance-p

Reputation: 1070

Convert encoded application/x-www-form-urlencoded post data to json object

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)

Upvotes: 2

Views: 11260

Answers (2)

pfg
pfg

Reputation: 3575

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

Upvotes: 2

Anand Siddharth
Anand Siddharth

Reputation: 977

You can actually post JSON as body.

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"
  },
  "dataType" : "json"
  "processData": false,
  "data": { "practice": ["Learning"] }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

Notice that theirs a new property which tells that data type to be posted is JSON and and now in data property the value is in JSON format instead of string.

Hope this solves your problem.

Upvotes: -1

Related Questions