我想通过转义“ /”来保存带有一个转义字符的json对象,因此我使用了字符串替换并将我的字符串转换为“ /” 然后我将其分配给对象变量并尝试控制台日志,它将自动转换为“ \ /”
我的初始数据集是base64字符串
这是我的代码段
示例字符串:data ="/9j/4AAQSkZJRgABAQAAAQABAAD//gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
var datawithescape= data.replace(/\//g, '\\/');
console.log("result 1"+ datawithescape);
var result ={
"id" : id,
"data":datawithescape
};
console.log("result 2" +result);
输出
结果1
"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
结果2
{
id :1
data : "\\/9j\\/4AAQSkZJRgABAQAAAQABAAD\\/\\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
}
我想要的是
{
id :1
data : "\/9j\/4AAQSkZJRgABAQAAAQABAAD\/\/gA+Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBkZWZhdWx0"
}
答案 0 :(得分:1)
您遇到的问题是console.log
用不同的方式为您格式化字符串。数据本身没有改变。
当console.log
显示一个对象时,它显示数据的完整内部表示形式,其中包括转义字符。当它格式化为字符串时,它将显示字符,而不是其转义形式。
考虑一下REPL中的这个较小的示例:
> let x = "\\/abc\\/"
'\\/abc\\/' <--- first character is an escaped backslash "\\"
> let y = {x: x}
{ x: '\\/abc\\/' } <--- first character in y.x is still an escaped backslash
> console.log(y)
{ x: '\\/abc\\/' } <--- same result when console.log shows 'y'
> console.log(x)
\/abc\/ <--- but here console.log displays x without the escape
> console.log(y.x)
\/abc\/ <--- similarly here for y.x
> let z = "\tHello"
> z
'\tHello' <--- when looking at z as an object we see "\t"
> console.log(z)
Hello <--- when looking at z as a string we see the tab expanded
在您的示例中,如果您执行console.log(result.data)
,则将看到它没有所需的双反斜杠。在显示对象而不是格式化的字符串时,console.log
会向您显示带有转义反斜杠的实际数据,因此显示为“ \”。
答案 1 :(得分:0)