如何使用JS将目标文件转换为JSON

时间:2015-04-02 10:40:34

标签: javascript json

我用HTML,CSS和Javascripts创建WP应用程序,现在我有一个问题: - 我使用openPicker.pickSingleFileAndContinue()从库中选择一张图片并从中创建一个文件:

var file = MSApp.createFileFromStorageFile(filePicked);

我使用console.log(文件),它打印:

[object File]
   {
      [functions]: ,
      __proto__: { },
      constructor: { },
      lastModifiedDate: [date] Thu Apr 02 2015 16:44:58,
      name: "WP_20150402_001.jpg",
      size: 1048405,
      type: "image/jpeg"
   }

现在,我的问题是:如何将其转换为格式为的JSON文件:

{file:
 [
  {
    modified: date] Thu Apr 02 2015 16:44:58,
    name: "WP_20150402_001.jpg",
    size: 1048405,
    type: "image/jpeg"
  }
 ]
}

请读,请帮助我。

1 个答案:

答案 0 :(得分:1)

var file = MSApp.createFileFromStorageFile(filePicked);

// Create POJO structured like the way we want.
var fileData = {
  file: {
    modified: file.lastModifiedDate,
    name: file.name,
    size: file.size,
    type: file.type
  }
}

// Convert data to JSON string.
var serializedData = JSON.stringify(fileData);

serializedData现在应包含以下值:

"{"file":{"lastModifiedDate":"2015-04-02T10:52:31.993Z","name":"WP_20150402_001.jpg","size":1048405,"type":"image/jpeg"}}"