-2

I am working on aws project which consist of VTL(Velocity template language) library and graphql schema. The database is also of aws particularly dynamodb. Now Its sending(mutation) data to db through "\". I wanted to know what does the meaning of "\"?

mutations.forEach((mutation) => {
  let details = `\\\"id\\\": \\\"$ctx.args.id\\\"`;

  if (mutation === "addLolly") {
    //details = `\\\"color1\\\":\\\"$ctx.args.lolly.color1\\\" , \\\"color2\\\":\\\"$ctx.args.lolly.color2\\\", \\\"color3\\\":\\\"$ctx.args.lolly.color3\\\", \\\"sender\\\":\\\"$ctx.args.lolly.sender\\\", \\\"reciever\\\":\\\"$ctx.args.lolly.reciever\\\", \\\"message\\\":\\\"$ctx.args.lolly.message\\\", \\\"link\\\":\\\"$ctx.args.lolly.link\\\"`;
    details = `\\\"color1\\\":\\\"$ctx.args.lolly.color1\\\" , \\\"color2\\\":\\\"$ctx.args.lolly.color2\\\" , \\\"color3\\\":\\\"$ctx.args.lolly.color3\\\" ,\\\"reciever\\\":\\\"$ctx.args.lolly.reciever\\\" ,\\\"sender\\\":\\\"$ctx.args.lolly.sender\\\" , \\\"message\\\":\\\"$ctx.args.lolly.message\\\" , \\\"link\\\":\\\"$ctx.args.lolly.link\\\"`;

  }
CBroe
  • 91,630
  • 14
  • 92
  • 150
  • 3
    Who ever did this tries to build JSON by hand, which is almost always a terrible idea... – Andreas Mar 18 '21 at 10:00
  • But basically, this is simple _escaping_ … https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_notation – CBroe Mar 18 '21 at 10:00
  • Basically in this case it means someone is building JSON by hand, which is almost never a good idea. It's ```\\``` followed by ```\"``` in a template literal. The ```\\``` puts an actual backslash into the resulting string, and the ```\"``` puts an actual `"` in the resulting string. So for instance, if we assume `$ctx.args.id` is `42`, then this: ```let details = `\\\"id\\\": \\\"$ctx.args.id\\\"`;``` puts the characters `\"id\": \"42\"` in `details`. Why do that? Can't say without more context, but it's unlikely to be best practice. – T.J. Crowder Mar 18 '21 at 10:01

1 Answers1

1

We have to add an extra backslash to a backslash in a string to escape them.

const str2 = '\\'; // is valid = 1 backslash
const str1 = '\'; // is invalid = error
const str3 = '\\\'; // is therefore invalid  = error
const str6 = '\\\\\\'; // is valid  = 3 backslashes
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63