如果包含反斜杠,则无法读取json属性

我试图从请求访问一个JSON,如:

var files = req.files.fileData[0]; // This contains multiple file data // initially it is like [object object] for(var i=0; i<files.length; i++){ var fileDataArr = JSON.stringify(files[i]); console.log("**********fileDataArr : "+fileDataArr); var attachmentId = fileDataArr.name.attachmentId; console.log("id : "+attachmentId); } 

JSON结构是我得到,而控制台fileDataArr是:

 {"domain":null,"_events":{},"_eventsCount":0,"size":5056,"path":"C:\\Users\\k7000649\\AppData\\Local\\Temp\\8eb4f7b82b5646cef78f9989bb3353b1","name":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}","type":"image/png","hash":false,"lastModifiedDate":"2017-08-22T11:25:03.380Z","_writeStream":{"_writableState":{"objectMode":false,"highWaterMark":16384,"needDrain":false,"ending":true,"ended":true,"finished":true,"decodeStrings":true,"defaultEncoding":"utf8","length":0,"writing":false,"corked":0,"sync":false,"bufferProcessing":false,"writecb":null,"writelen":0,"bufferedRequest":null,"lastBufferedRequest":null,"pendingcb":0,"prefinished":true,"errorEmitted":false,"bufferedRequestCount":0,"corkedRequestsFree":{"next":null,"entry":null}},"writable":false,"domain":null,"_events":{},"_eventsCount":0,"path":"C:\\Users\\k7000649\\AppData\\Local\\Temp\\8eb4f7b82b5646cef78f9989bb3353b1","fd":null,"flags":"w","mode":438,"autoClose":true,"bytesWritten":5056,"closed":true},"length":5056,"filename":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}","mime":"image/png"} 

结构是有效的,但反斜杠

我试图parsing的JSON删除反斜杠,但它会引发一个像SyntaxError:意外的令牌o的错误,当我试图从JSON访问任何数据(fileDataArr.name.attachmentId)它会引发一个错误,如:

 TypeError: Cannot read property 'attachmentId' of undefined at exports.xhr_upload_multi_attachment (D:\Harmony_Trunk\Development\Asset-Editor\build\harmony_development\routes\xhr_upload_attachment.js:122:39) 

我尝试用正则expression式replace反斜杠(/ \ g /,''),这很好,但我有JSON文件path,因此文件path丢失。

请告诉我解决这个问题。

看起来它已经被parsing了,但是它在name属性中包含了嵌套的JSON数据。

请注意,双引号仅在该属性中转义。 这是因为你对对象进行了string化,这使得该属性编码了两次。

 "name":"{\"fileName\":\"wiproNewIcon.png\",\"fileType\":\"image/png\",\"attachmentId\":\"99c148f3f5c1\",\"restrictedFileSize\":\"25690112 \"}" 

所以不要串联,而是在循环中parsing这个name属性:

 var parsedName = JSON.parse(files[i].name); console.log(parsedName.attachmentId); 

如果这样做,然后尝试找出为什么这一个属性保持与其余编码不同的数据。 无论是产生你的数据似乎是编码,其余的一个属性分离..