How can I serialize an input File object to JSON?

JavascriptJsonFile

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

You have to read the file content using the FileReader API. The File object does not contain the file content (it is just a pointer toward the file, which allows you to read it later).

You can check out this HTML5Rocks article to find out more about the usage of this API.

var file = getAFile( );

var success = function ( content ) {
  console.log( JSON.stringify( content ) ); }

var fileReader = new FileReader( );
fileReader.onload = function ( evt ) { success( evt.target.result ) };
fileReader.readAsText( file );

Solution 3 - Javascript

In case anyone is still looking for a solution to this please see my answer on a different post and working example on JSFiddle.

JS:

function getFiles(){
    var files = document.getElementById("myFiles").files;
    var myArray = [];
    var file = {};
  
    console.log(files); // see the FileList

    // manually create a new file obj for each File in the FileList
    for(var i = 0; i < files.length; i++){
   
      file = {
          'lastMod'    : files[i].lastModified,
          'lastModDate': files[i].lastModifiedDate,
          'name'       : files[i].name,
          'size'       : files[i].size,
          'type'       : files[i].type,
      } 
    
      //add the file obj to your array
      myArray.push(file)
    }
  
    //stringify array
    console.log(JSON.stringify(myArray));
}

HTML:

<input id="myFiles" type="file" multiple onchange="getFiles()" />

Solution 4 - Javascript

You just need a custom replacer:

function stringify(obj) {
	const replacer = [];
	for (const key in obj) {
		replacer.push(key);
	}
	return JSON.stringify(obj, replacer);
}

const json = stringify(file);
console.log(file);
console.log(json);

Now you should see:

File {name: "xyz.jpg", type: "image/jpeg", size...}
'{"name":"xyz.jpg","type":"image/jpeg","size"...}'

Solution 5 - Javascript

Instead of looping through, or rather extracting each key one after the other, i came up with this function and i've used it image input.

const fileObject = e.target.files[0];

important notice

//dont use shorthand for of loop
for (const [key, value] in Object.entries(x)) 
it can't loop through a file object in JS 

Use this code instead

const imageObject = {};

for (const key in fileObject) {
    const value = fileObject[key];
    const notFunction = typeof value !== "function";
    notFunction && (imageObject[key] = value);
}

console.log(imageObject) // => should give you a normal JS object now

Solution 6 - Javascript

When you pass a json string Javascript internally trnsform it to Json object and hence no need to parse it.

follow steps in case of of json file ->

$('#inp_import_template')[0].files[0]

Now your json file is transformed to json object (Javascript).

Solution 7 - Javascript

var obj = {
  name: 'dashu3f'
};

var stringObj = JSON.stringify(obj);
console.log(typeof stringObj);
console.log(stringObj);

open terminal this Folder file and run node json.js

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeacemakerView Question on Stackoverflow
Solution 1 - Javascriptahmed hamdyView Answer on Stackoverflow
Solution 2 - JavascriptMaël NisonView Answer on Stackoverflow
Solution 3 - JavascriptTammy TeeView Answer on Stackoverflow
Solution 4 - JavascriptkevlenedView Answer on Stackoverflow
Solution 5 - JavascriptChukwuEmekaView Answer on Stackoverflow
Solution 6 - JavascriptNew BeeView Answer on Stackoverflow
Solution 7 - JavascriptyousefView Answer on Stackoverflow