How to serialize File object to JSON? [duplicate] - javascript

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.

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.

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 );

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()" />

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"...}'

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

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).

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

Related

formdata.append a combined associative array

I am trying to append the data from two associative arrays I have so I can send it to my php file to then write to the server.
I combined my two arrays by doing the following:
var allInputs = {... reqfields,... otherfields};
Up until here I am getting all the values I need and I am seeing them on my console but I don't know how to use the formData.append() for these types of arrays.
It looks like the signature of formData.append is given by:
formData.append(name, value);
(*you could also add a filename as a third argument)
Assuming the reqFields and the otherFields are objects of the form:
{
fieldName1: response1,
fieldName2: response2,
...
}
you could use Object.entries to iterate over the properties and call formData.append on each.
const allInputs = {...requiredFields, ...otherFields};
for (let [key, value] of Object.entries(allInputs)) {
formData.append(key, value);
}
*Note that Object.entries isn't natively supported in Internet Explorer. You can also use Object.keys(allInputs).forEach(...) to iterate over all of the keys in allInputs. There are other ways, too.
Append this object to your FormData as a JSON string:
const reqfields = { a: 1, b: 2 };
const otherfields = { c: 3 };
const allInputs = {... reqfields,... otherfields};
const formdata = new FormData();
formdata.append( 'your_field_key', JSON.stringify(allInputs) );
/*
// then you can send it to your server
fetch( server_url, {
method: "POST",
body: formdata
});
*/
// for SO demo we just log the request's body as text
new Response( formdata ).text()
.then( console.log );
And then on your server side you can retrieve it from the multipart data using the field key you used and simply parse it:
<?php
if ( isset($_POST["your_field_key"]) ) {
$fields = json_decode($_POST["your_field_key"]);
...

Load a JSON file into a JS object

I try to load a json file into a JavaScript var but it just doesn't work out.
var jsonString = JSON.stringify('./test.json');
var obj = JSON.parse(jsonString);
console.log(obj.details.ProductID);
it says that it can't read property ProductID of undefined.
What am I doing wrong here ?
You need to make an AJAX call to get the file. $.getJSON was intended for exactly this purpose:
$.getJSON('./test.json', function(obj) {
console.log(obj.details.ProductID);
});
If you are using jQuery:
$.getJSON( "/test.json", function( obj ) {
console.log(obj.details.ProductID);
});
JSON.stringify() first argument needs to be a valid JSON string, not a file.
You need to use AJAX to retrieve file from server:
$.getJSON('./test.json', function(responseObject){
var obj = responseObject
console.log(obj)
})
In case it helps anyone, just use this:
const dataObjectFromFile = require('./path/to/datafile.json');

JSON array-like object, add item

I have a JSON file which contains:
[{"id":1,"first_name":"Judith","email":"jshaw0#wikipedia.org"},
{"id":2,"first_name":"Sarah","email":"sross1#infoseek.co.jp"},
{"id":3,"first_name":"Dorothy","email":"dgreene2#posterous.com"},
{"id":4,"first_name":"Christine","email":"cnichols3#techcrunch.com"},
{"id":5,"first_name":"Theresa","email":"trogers4#xrea.com"},
{"id":6,"first_name":"Rebecca","email":"rpeterson5#mlb.com"},
{"id":7,"first_name":"Chris","email":"cbailey6#yellowpages.com"},
{"id":8,"first_name":"Howard","email":"hbailey7#miibeian.gov.cn"},
{"id":9,"first_name":"Sara","email":"ssimpson8#techcrunch.com"},
{"id":10,"first_name":"Lois","email":"lmartinez9#dion.ne.jp"},
{"id":11,"first_name":"Jeffrey","email":"jhalla#intel.com"},
{"id":12,"first_name":"Teresa","email":"tcampbellb#usnews.com"},
{"id":13,"first_name":"Susan","email":"skingc#wired.com"},
{"id":14,"first_name":"Richard","email":"rpattersond#omniture.com"},
{"id":15,"first_name":"Ronald","email":"rgreenee#wordpress.org"}]
I want to add one more element to it but I can't figure it out how.
I have the following node code:
var jsonfile = require('jsonfile');
var util = require('util');
var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
jsonObj = obj;
new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
//jsonObj.push(new_obj)
console.log(typeof jsonObj);
/*jsonfile.writeFile(file, jsonObj, function (err) {
console.error(err)
})*/
});
I've tried to use push method, but obviously is not working because it is an object not an array, even if it looks as an array. Which would be a good way to add another row at the end of the object (or array - I'm confused)?
I believe you're forgetting to parse JSON. After reading the file, your code should be:
jsonObj = JSON.parse(obj);
instead of straight assignment.
Declare the variable
var new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
And then use push() as you have done already. Give it a try. It will work only if obj is json object as you mentioned in question.

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.
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.
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 );
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()" />
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"...}'
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
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).
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

JSON anonymous type property undefined?

in my mvc3 roject, I return the Json object:
return Json(new { ID = guid, FileName = file.FileName, FullPath = filename });
then, in the JS code, I try to acces to the fields, e.g:
onComplete: function (event, queueId, fileObj, response, data) {
alert(response.ID); //test
}
but i get the undefined message. If i just get the alert(response); I see the valid object:
{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}
so how to access to that properties ?
You're probably seeing the JSON text that needs to be parsed into JavaScript data structures.
var parsed = JSON.parse(response);
alert( parsed.ID );
Without parsing it, you're trying to access the ID property of a String object.
var str = '{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}';
alert( str.ID ); // undefined

Categories

Resources