简体   繁体   中英

Javascript Parsing JSON with Escape Characters

So I have a JSON object that is returned from an Android Pay API call that I need to pull the data out and process it. Problem is that it contains backslashes that must be preserved. I have looked at lots of threads on this but nothing seems to work. How can I parse out the key/value pairs from data below and preserve the backslashes in the data?

{"ephemeralPublicKey":"BE1Ai3\/HjtEon0JAz+9jK8GmF9vzmXpDACcpjsXDD5EkP7HmhdXrNjVMdi58itYNGH6HoZvlOY65qvHWRwS0pu8=","encryptedMessage":"BIrMosJ9dQSeCL0ImJPhml3++grM6AvW9qLkTkp6I\/gt1q+JsFB9rm9Ndzdjd7UuN\/RJm6osMHd1UDIi84VlQljJKMQnRQKrQrqx15jlNOBlGrALOTY3TQIYyWOvMB8I\/Kr6yFduvy+b2IVR+3GPDjI4J3PKHd+xPLh4WvXhmBckda54T3vVW\/2Toxi02IC1w\/n5AkTlKfem6XTvw9sC","tag":"GEyeDyeNrXn3T2GYHFOL4WeQLBRBVt7PCKmr9OfJa3M="}

I see the code is working, what is the point in your question?

you should escape the backslash character, like this.

var str = '{"ephemeralPublicKey":"BE1Ai3\\/HjtEon0JA"}';//...string response from api 
var obj = JSON.parse(str.replace('\\/','\\\\/'));
obj.ephemeralPublicKey

I figured it out.

var data = {"ephemeralPublicKey":"BE1Ai3\/HjtEon0JAz+9jK8GmF9vzmXpDACcpjsXDD5EkP7HmhdXrNjVMdi58itYNGH6HoZvlOY65qvHWRwS0pu8=","encryptedMessage":"BIrMosJ9dQSeCL0ImJPhml3++grM6AvW9qLkTkp6I\/gt1q+JsFB9rm9Ndzdjd7UuN\/RJm6osMHd1UDIi84VlQljJKMQnRQKrQrqx15jlNOBlGrALOTY3TQIYyWOvMB8I\/Kr6yFduvy+b2IVR+3GPDjI4J3PKHd+xPLh4WvXhmBckda54T3vVW\/2Toxi02IC1w\/n5AkTlKfem6XTvw9sC","tag":"GEyeDyeNrXn3T2GYHFOL4WeQLBRBVt7PCKmr9OfJa3M="};

var obj = JSON.parse(data.replace(/\\/g, '\\\\'));
console.log("Value: " + obj.ephemeralPublicKey);

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