Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize an input File object to JSON?

I want to convert an HTML input file to a JSON string like this:

var jsonString = JSON.stringify(file); console.log( file ); console.log( jsonString ); 

Now, in my Firebug it logs as:

File { size=360195, type="image/jpeg", name="xyz.jpg", mehr...}  Object {} 

Why is the jsonString empty?

Background info: I want to send the file-reference with JSONP to another PHP server.

Additional Information: I want to convert only the file-pointer (reference) to a string, to send it via GET.

like image 247
peacemaker Avatar asked Jun 10 '14 10:06

peacemaker


People also ask

How to stringify a JSON file?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

What JavaScript method is used to serialize a JSON object?

JSON.stringify() The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What is JSON serialization in JavaScript?

JSON serializer converts an object to its string. The reverse is also possible which is known as Deserialization. JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format.


1 Answers

It is not possible to directly convert a File object into JSON using JSON.stringify in Chrome, Firefox and Safari.

You can make a work around to convert File object to string using JSON.stringify

Ex:

// get File Object   var fileObject = getFile();  // reCreate new Object and set File Data into it var newObject  = {    'lastModified'     : fileObject.lastModified,    'lastModifiedDate' : fileObject.lastModifiedDate,    'name'             : fileObject.name,    'size'             : fileObject.size,    'type'             : fileObject.type };     // then use JSON.stringify on new object JSON.stringify(newObject); 

You can also add the toJSON() behavior to your File object

EX:

// get File Object   var fileObject = getFile();  // implement toJSON() behavior   fileObject.toJSON = function() { return {    'lastModified'     : myFile.lastModified,    'lastModifiedDate' : myFile.lastModifiedDate,    'name'             : myFile.name,    'size'             : myFile.size,    'type'             : myFile.type  };}     // then use JSON.stringify on File object JSON.stringify(fileObject); 

Note: send a File Object to server using the POST HTTP method.

like image 94
ahmed hamdy Avatar answered Sep 23 '22 10:09

ahmed hamdy