How to Serialize an Input File Object to JSON

How to convert FormData (HTML5 object) to JSON

You could also use forEach on the FormData object directly:

var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);


UPDATE:

And for those who prefer the same solution with ES6 arrow functions:

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);

UPDATE 2:

And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):

var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);

Here a Fiddle demonstrating the use of this method with a simple multi select list.

UPDATE 3:

As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData object directly without converting it. As simple as this:

var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);

See also Using FormData Objects on MDN for reference:

UPDATE 4:

As mentioned in one of the comments below my answer the JSON stringify method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify.

In the description is also mentioned that:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

This means that you can supply your own toJSON serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.

How to deserialize JSON string from file input

Ok here is my answer. I went through your code and there are quite few issues. If I need to fix every thing for you it gone take some time. but here are some suggestion and you can take it to the next level.

  1. You are trying to update a file with multipart form but you are trying to fetch a string. It is correct that you the file contains the string of json, but it is still a file. so we need to handle that part.

  2. So you are both trying to show data using JavaScript and in view. In my example I have focused on showing data in your IndexDeserialized and JavaScript part is left for another question.

Here what I did and suggest:

In your controller, remove following method and replace it with the one I posted:

[HttpPost]
public IActionResult ImportForm(string jsonString)
{
TableDemo model = JsonSerializer.Deserialize<TableDemo>(jsonString);
return View("IndexDeserialized", model);
}

The new method, this is just simple example that can read the file you uploaded and return the result of it to the same page.

[HttpPost]
public async Task<IActionResult> ImportFormOnPost()
{
string jsonString = string.Empty;

if (HttpContext.Request.Form.Files[0] != null)
{
var file = HttpContext.Request.Form.Files[0];
await using (MemoryStream ms = new MemoryStream())
{
await file.CopyToAsync(ms);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
}
}

TableDemo model = JsonSerializer.Deserialize<TableDemo>(jsonString);
return View("IndexDeserialized", model);
}

In your ImportForm, you are missing action, in this case we are posting to ImportFormOnPost method:

<form name="form" method="post" enctype="multipart/form-data" action="ImportFormOnPost">
<div class="form-group">
<input type="file" class="form-control" name="file" />
</div>
<div id="jsonContent">

</div>

<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>

<div style="margin-top:15px">
<output form="uploadForm" name="result"></output>
</div>
</form>

And finally we are presenting your data in IndexDeserialized:

@model FileUploaderApp.Models.TableDemo
<p>Number for locations: @Model?.Locations?.Count</p>

@if (Model != null)
{
foreach (var user in @Model.Users)
{
<p>@user.FirstName @user.LastName</p>
}
}

It is possible to show your data as JSON object in using JavaScript in your front-end, but I think this part is a question for its own.

And remember this is just example, you can do a lot on top of it.

The final result looks like this:

Sample Image

For what I did, I got some reading from Microsoft about file uploading check this resource code example of file upload.

How to convert an image from input to json, send it in fetch to php and then send it on server via PHPMailer?

Have a look at the source for the addAttachment method of PHPMailer. (Pasted to the end of this answer.)

You're passing an object ($data-> jsonObject) where the method expects a string corresponding to a file path.

The solution could take many forms - you've got to find some way to take the submitted data and save at least a temporary file to the server before sending it as an attachment via PHPMailer.

You're already sending the rest of the data in a Content-type: application/json format, but following some of the approaches in this answer which uses an enctype of multipart/form-data on the form could be one way.

Alternatively, you might convert the image's data to base64 and POST it with the rest of your JSON data. Then, on the other side, decode & save to /tmp/{filename}.ext and reference THAT as the first arg to $mail->addAttachment.

/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
* If you need to do that, fetch the resource yourself and pass it in via a local file or string.
*
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
* @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
* @param string $disposition Disposition to use
*
* @throws Exception
*
* @return bool
*/
public function addAttachment(
$path,
$name = '',
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'attachment'
) {
...
}

How can I create a json file from object with serializer?

I think you're assigning the key incorrectly. A key should be assigned like this:

$arr['keyName'] = $value

You're assigning it like this:

$arr->{"keyName"} = $value

I hope I helped you with this answer!

Javascript can you serialize a File object

As a matter of principle, what you are asking for will not be possible. If it were possible to have some text which represented the file object, then you could construct that text from scratch, unserialize it, and thus get access to files the user did not grant permission to.

(The exception to this is if the representative text is some sort of robustly-secret bitstring (cryptographically signed, or a sparse key in a lookup table) that only the browser could have given out in the first place — but I expect if that feature existed, it would be documented and you would have found it already.)

Serializing a javascript class object?

You can use JSON.stringify, but be aware that it only serialize properties, not methods. So to unserialize an object, just create a dummy instance and use Object.assign to update the properties using the retrieved object:

function serialize(instance) {
var str = JSON.stringify(instance);
// save str or whatever
}

function unserialize(str, theClass) {
var instance = new theClass(); // NOTE: if your constructor checks for unpassed arguments, then just pass dummy ones to prevent throwing an error
var serializedObject = JSON.parse(str);
Object.assign(instance, serializedObject);
return instance;
}

Example:

function serialize(obj) {    var str = JSON.stringify(obj);    return str;}
function unserialize(str, theClass) { var instance = new theClass(); var serializedObject = JSON.parse(str); Object.assign(instance, serializedObject); return instance;}
// TEST CLASS
class TestClass { constructor(a, b) { this.a = a; this.b = b; }
sum() { return this.a + this.b; }}
// USAGE
var instance = new TestClass(5, 7);
var str = serialize(instance);
var retrievedInstance = unserialize(str, TestClass);
console.log(retrievedInstance.sum());

How to serialize db.Model objects to json?

Since I could not find an appropriate solution I wrote my own, which is not exactly a JSON serializer, but a Javascript serializer

from google.appengine.ext import db
from google.appengine.api.datastore_types import *

def dumpStr(obj):
return "'" + obj + "'"

def dumps(obj):
if isinstance(obj, str):
return dumpStr(obj)
elif obj == None:
return None
elif isinstance(obj, list):
items = [];
for item in obj:
items.append(dumps(item))
return '[' + ','.join(items) + ']'
elif isinstance(obj, datetime.datetime):
return "new Date('%s')" % obj.ctime()
properties = [];
for property in dir(obj):
if property[0] != '_':
value = obj.__getattribute__(property)
valueClass = str(value.__class__)
if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):
value = dumps(value)
if value != None:
properties.append("'" + property + "':" + value)
if len(properties) == 0:
return str(obj)
else:
return '{' + ','.join(properties) + '}'


Related Topics



Leave a reply



Submit