k.vincent
k.vincent

Reputation: 4133

How To escape backslash in JSON object?

I send a POST Request with JSON Objet in body to an application which is expecting this kind of value:

{
   "input": {
      "queryFilter": "mail eq \"[email protected]\""
   }
}

The Request works fine and I get a response 200.

Then I want to send the same Request via UI/Form and try to pass it as JSON Object as following:

input: {
    queryFilter: '"mail eq \"' + mail + '\" "'
}

Which ends in: {input: {queryFilter: ""mail eq "[email protected]" ""}}

This is syntactically not correct and not as the working JSON via Postman. Also trying it as:

input: {
    queryFilter: {
       mail: mail
    }
}

didn't help.

I have been checking some postings like: How to escape Backslash in Javascript object literal, but they look handling other kind of issues So, how would it be possible to build the JSON Objet in the JavaScript file correctly so that it ends up exactly like the one working on Postman?

Upvotes: 2

Views: 10893

Answers (2)

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

try this :

var mail = "[email protected]";
var mailValue = "mail eq " + "\\\"" + mail + "\\\"";
var result = JSON.stringify(Object.create(null, {
  input: {
    value: {
      queryFilter: mailValue
    },
    enumerable: true
  }
}));

console.log(result);

Upvotes: 1

3Dos
3Dos

Reputation: 3487

The error here is not the double quote escaping with backslashes but the actual double quotes wrapping your json value.

Remove them like the following and you should be good to go !

const mail = '[email protected]'
const obj = {
  input: {
    queryFilter: 'mail eq "' + mail + '" '
  }
}

console.log(JSON.stringify(obj))

Upvotes: 2

Related Questions