Thanhtu150
Thanhtu150

Reputation: 91

How to convert object file to JSON with JS

i'm creating WP app with HTML, CSS and Javascripts, now i have a question: - I using openPicker.pickSingleFileAndContinue() to pick a picture from library and i create a file from it:

var file = MSApp.createFileFromStorageFile(filePicked);

I use console.log(file), it print:

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

Now, my question is: How can i convert it to JSON file with format:

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

Tks for read, plz help me.

Upvotes: 0

Views: 5945

Answers (1)

Jon Koops
Jon Koops

Reputation: 9261

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 should now contain something like the following value:

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

Upvotes: 1

Related Questions