简体   繁体   中英

how to filter “\” from a json string in javascript

I receive a json string at my node js server which looks like this:

{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}

The reason i put in the "\\" is because the string is made in C and the \\ is used to escape the " which otherwise ends the string.

The code i use now is:

 app.get('/add/:jsonString', function(req, res){
        var json = JSON.parse(req.params.jsonString);
 });

Is there a way to only delete the \\'s in my string?

Why do you want to remove it, it's not necessary ?

var a ="{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}";
console.log(JSON.parse(a));
// give Object { gID: 1, sID: 18, T: "Parking" }

EDIT

Use Url encode to pass your get json

var str = encodeURIComponent("{\"gID\":1,\"sID\":18,\"T\":\"Parking\"}");
// send your request
request.get({uri:"website/api?data="+str}, ...

And in server, decode uri then parse

   var string = decodeURIComponent(req.query.data);
  var obj = JSON.parse(string);

If you want to remove the "\\", try the replace method with a regex pattern:

str.replace(/\\/g, "")

The g flag is used to replace all occurences of the char "\\", while the first "\\" is an escape character.

For further details, consult MDN

I would suggest that you pass JSON into your application using a POST request, as there are plenty of characters that aren't URI-safe.

However, you can use the unescape method from the built in querystring module.

const qs = require('querystring');

app.get('/add/:jsonString', function(req, res){
    const json = JSON.parse(qs.unescape(req.params.jsonString));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM