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

时间:2017-08-22 13:07:17

标签: javascript node.js express

我正在尝试从请求中访问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);
        }

当控制台fileDataArr为:

时,我正在获取JSON结构
{"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"}

结构有效但反斜杠

我试图解析JSON以删除反斜杠,但它会抛出类似SyntaxError:Unexpected token 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)

我尝试使用正则表达式替换反斜杠(/ \ g /,&#39;&#39;),它很好,但我在JSON中有文件路径,因此缺少文件路径。

请告诉我解决此问题。

1 个答案:

答案 0 :(得分:3)

看起来它已经被解析但它包含name属性的嵌套JSON数据。

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

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

所以根本不进行字符串化,但在循环中解析name属性:

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

如果可行,那么尝试弄清楚为什么一个属性使用与其余属性不同的编码来保存其数据。无论生成什么数据,似乎都会编码一个属性与其余属性分开..